Mongoose: Get full list of users
Well, if you really want to return a mapping from _id
to user
, you could always do:
server.get('/usersList', function(req, res) { User.find({}, function(err, users) { var userMap = {}; users.forEach(function(user) { userMap[user._id] = user; }); res.send(userMap); });});
find()
returns all matching documents in an array, so your last code snipped sends that array to the client.
If you'd like to send the data to a view pass the following in.
server.get('/usersList', function(req, res) { User.find({}, function(err, users) { res.render('/usersList', {users: users}); }); });
Inside your view you can loop through the data using the variable users
This is just an Improvement of @soulcheck 's answer, and fix of the typo in forEach (missing closing bracket);
server.get('/usersList', (req, res) => User.find({}, (err, users) => res.send(users.reduce((userMap, item) => { userMap[item.id] = item return userMap }, {})); ); );
cheers!