I'm trying to display a MongoDB collection of employees into Pug. I know it has something to do with the first 'data' object. I cannot figure out how to render the data within the array.
MongoDB collection:
{
"data":[
{
"active":true,
"userName":"example",
"employeeDetails":{
"personalDetails":{
"firstName":"Dennis",
"lastName":"Glover",
"emailAddress":"example#example.com"
}
}
},
{
"active": false,
"userName": example2,
"employeeDetails": {
"personalDetails": {
"firstName": "Ben",
"lastName": "Dover",
"emailAddress": "example2#example.com"
}
}
},
]
}
Express:
MongoClient.connect(url, function(err, db) {
if (err) {
console.log('Unable to connect to the Server', err);
} else {
console.log('Connection established to', url);
var employeecollection = db.collection('employees');
// Find all employees
employeecollection.find({}).toArray(function(err, employeeResult) {
if (err) {
res.send(err);
} else if (employeeResult.length) {
res.render('employeelist', {
'employeelist': employeeResult,
});
} else {
res.send('No documents found');
}
db.close();
});
};
});
Pug:
table
each employee in employeelist
tr#employee_list_item
td #{employee.userName}
I have fiddled around got it working with Angular2 using ng-repeat, however I cannot seem to get it to render in Pug unless I strip out the 'data' object in the array (which needs to be there).
As much as I can see employeelist[0].data is the array you want to iterate on.
Change employeelist to employeelist[0].data
table
each employee in employeelist[0].data
tr#employee_list_item
td #{employee.userName}
Update. Alternative method:
As Mohit suggested, if you send from the route itself, then your original code will work.
// Find all employees
employeecollection.find({}).toArray(function(err, employeeResult) {
if (err) {
res.send(err);
} else if (employeeResult.length) {
res.render('employeelist', {
'employeelist': employeeResult[0].data,
});
} else {
res.send('No documents found');
}
db.close();
});
Then, in your view:
Pug
table
each employee in employeelist
tr#employee_list_item
td #{employee.userName}
Hope this helps you!
Related
my Schema :
var schoolSchema = new mongoose.Schema({
name: String,
classes:[
{
c_name:String,
c_strn:String,
students:[
{s_name:String,
s_roll:String,
s_address:String
}
]
}
],
});
var school = mongoose.model('school',schoolSchema);
Sample Doc :
var sainik = new school({name:'sain',
classes:
[
{
c_name:'1(one)',
c_strn:'100',
students:[
{
s_name:"Leo",
s_roll:"17",
s_address:"strt24",
},
{
s_name:"Kyle",
s_roll:"18",
s_address:"strt24",
}
]//array of students
}
]//array of classes
});
sainik.save().then(()=>console.log("Save it"));
Code :
app.get('/home/:id/:cid',function(req, res){
school.find().exec(function(err,data){
if (err){
console.log(err);
}
else{
console.log(data);
res.render("classDet",{data:data});
}
})
});
Here i need to know how to get access to the individual classes using the class id and to print the array of students as list in the "classDet"
Basically I am creating a school management system in which there will be many classes and inside that classes will be list of students.
I want to print all the students in each classes only when the parent class is access.
You can try either one of these :
app.get('/home/:id/:cid', function (req, res) {
school.find({ id: id, 'classes.c_id': cid }, { _id: 0, 'classes.c_id.$.students': 1 }).lean().exec(function (err, data) {
if (err) {
console.log(err);
}
else {
console.log(data);
res.render("classDet", { data: data });
}
})
})
Test : MongoDB-Playground
app.get('/home/:id/:cid', function (req, res) {
school.aggregate([{ $match: { id: id } }, { $unwind: '$classes' }, { $match: { 'classes.c_id': cid } }, { $project: { _id: 0, students: '$classes.students' } }]).exec(function (err, data) {
if (err) {
console.log(err);
}
else {
console.log(data);
res.render("classDet", { data: data });
}
})
})
Test : MongoDB-Playground
Note : There will be a slight difference in both results, you can test it & choose one out of those, Also keep in mind if in case id from request is being searched against _id in DB then you need to convert id string to ObjectId() before using it in queries. Also we're using .lean() in .find() to convert mongoose docs into Js objects in order to access keys in data while working on it in code.
i'm trying to insert a new document in my Mongo database like this:
MongoClient.connect(MongoURL, function(error, database) {
var collection;
if (error) {
console.log(error);
}
collection = database.collection(job);
collection.insert(json, function(error, result) {
if (error) {
return console.log(error);
} else {
return console.log(result);
}
});
});
And is working, but not like i want.
The 'json' is an array of objects, like this:
json = [
{
"name": "Paulo"
},
{
"name": "José"
}
....
]
So, my code is creating one document for object, and i want create just one document with the objects inside a property called json:
{
json: [
{...},
{...},
{...}
]
}
Is this possible?
I tried to use insertMany, also.
Thanks.
Please try this one,
var obj = {};
obj.json = json;
col.insert(obj, function(error, result) {
if (error) {
return console.log(error);
} else {
return console.log(result);
}
});
Let's say I have this schema
{
jedi: [{
name:String
lightsaber_color:String
]}
}
I want to return all and only the names of them.
I tried
Jedi.find({})
.select('jedi.name')
.exec(function (err, jedi) {
if (err) {
console.log("nothing found")
}
}
It returns me nothing, while this code returns me everything.
Jedi.find({})
.select('jedi')
.exec(function (err, jedi) {
if (err) {
console.log("nothing found")
}
}
I see that jedi is an array so I think that .select('jedi.name') may not work for this reason.
What is the right syntax to do so?
You can try with this
Jedi.find({}, {'jedi.name':1}, function (err, jedi) {
if (err) {
console.log("nothing found")
}
else{
console.log(jedi);
}
}
i am inserting data into mongodb using mongodb driver in nodejs.
var mongodb = require('mongodb');
var insert = function(uri, collectionName, data, next) {
mongodb.MongoClient.connect(uri, function(err, driverDb) {
if(err) {
next(err);
} else {
driverDb.collection(collectionName).insert(data,function(err,result) {
if(err) {
next(err);
} else {
driverDb.close(function (err) {
if(err) {
next(err);
} else {
next(null,result);
}
});
}
});
}
});
};
insert('mongodb://localhost/mean-test','testcol',{
a : 'Apple',
b : [ { ba: 'Boy' }, {bb : 'Bird'} ]
}, function(err,models) {
console.log(models);
});
The above result into following:
[{a:'Apple', b : [[Object]] }]
How do i achieve this :
[{_id:ObjectId("someid"), a:'Apple', b : [{_id:ObjectId("someid"), ba: 'Boy' }, {_id:ObjectId("someid"), bb : 'Bird'}] }]
Please note i do not want to use any other npm module except of mongodb.
also i want to insert in one db query.
Your objects are inserting correctly, it's just that console.log only shows two levels of object detail by default. To show all object levels you need to call util.inspect directly so you can control that:
console.log(util.inspect(models, {depth: null}));
I have some collections shown like below which is holding relationships, relation between testMaster and testDoc is holding inside the testDocMaster
For eg:
testMaster {
_id: "Schema.Objectid",
name: "String" //master name
}
testDoc {
_id : Schema.ObjectId,
name: "String", //doc name
other datas
}
testDocMaster {
masterId: "_id of the testMaster table",
docId : "_id of the above testDoc"
}
For each master entry, we are expecting many relations,
what would be the best way to fetch the data from the testDoc table, if I have the masterId.
I got it working using this:
// GLOBAL ARRAYS FOR STORING COLLECTION DATA
var collectionOne = [];
var collectionTwo = [];
app.get('/', function(req, res){
MongoClient.connect("mongodb://localhost:27017/michael", function(err, db) {
if(!err) {
console.log("We are connected");
}
db.collection("collectionOne", function(err, collection) {
collection.find().sort({order_num: 1}).toArray(function(err, result) {
if (err) {
throw err;
} else {
for (i=0; i<result.length; i++) {
collectionOne[i] = result[i];
}
}
});
db.collection("collectionTwo", function(err, collection) {
collection.find().sort({order_num: 1}).toArray(function(err, result) {
if (err) {
throw err;
} else {
for (i=0; i<result.length; i++) {
collectionTwo[i] = result[i];
}
}
});
});
// Thank you aesede!
res.render('index.html', {
collectionOne: collectionOne,
collectionTwo: collectionTwo
});
});
});
});
Now, for some reason when Node restarts, and I hit refresh, it doesn't render HTML into the front-end. However, any subsequent refresh renders the page correctly.
Assuming your testDocMaster schema uses ObjectId types that ref the other two collections you can use Mongoose's query population support to help with this:
TestDocMaster.findOne({ masterId: masterId})
.populate('docId')
.exec(function(err, testDocMaster) {
// testDocMaster.docId is populated with the full testDoc for the
// matching _id
});