Im trying to find all documents in a DB using mongoose but I cant do it
I want to do it this way but I don't know what's wrong with it
app.get('/users', function (req, res){
User.find({}, 'name', function(err, user){
if(err){
console.log(err);
}else{
res.render('user-list', {
name : user.name
});
console.log('retrieved list of names' + user.name);
}
})
})
When I use User.findOne({}, 'name', function(err, user){..
I get back the first doc which is what I would expect. Please explain why the code above is not allowing me to get all documents. I feel like I'm using it the right way as show in the mongoose doc
Edit
thanks for help guys
i did like this:
app.get('/users', function (req, res){
User.find({}, 'name', function(err, users){
if(err){
console.log(err);
}else{
res.render('user-list', {
name : users.map(function(doc){
return doc.name + "<br>"
})
});
console.log('retrieved list of names' + users.name);
}
})
})
can some one please help me with getting each name on a new line the "<br>"
shows up on the page but it doesn't make a new line "<br>,Joe<br>,mike<br>"
Jade: extend layout
block content
p list of users #{name}
app.get('/users', function (req, res){
User.find({}, 'name', function(err, users){
if(err){
console.log(err);
} else{
res.render('user-list', users);
console.log('retrieved list of names', users.length, users[0].name);
}
})
});
As said in the comments, find
can find many objects, so it returns an array as contrasted with findOne
that returns a single object. Adjust for that as above and you should be back on track.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With