Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find all documents using mongoose

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} 
like image 768
jack blank Avatar asked Mar 19 '23 00:03

jack blank


1 Answers

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.

like image 150
Peter Lyons Avatar answered Apr 02 '23 19:04

Peter Lyons