jack blank
jack blank

Reputation: 5203

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} 

Upvotes: 4

Views: 25476

Answers (2)

app.get(`/users`, async (req,res)=>{
  try{
    const users = await User.find({}).exec()
    users && res.render('user-list',users)
  }catch(error){
   res.status(500).json({error})
  } 
})

//OR

app.get(`/users`, async (req,res)=>{
  try{
    const users = await User.find({}).exec()
    const list = new Array()
    for(let row of users){
      list.push(`${users.name}<br>`)
    }
    list ? res.status(200).send(list) : res.status(200).json({message: 'Users list is empty'}) 
  }catch(error){
   res.status(500).json({error})
  } 
})

In second example you send to client a text line!!!

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 145994

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.

Upvotes: 8

Related Questions