Mongoose: Get full list of users

I have tried to use Mongoose to send the list of all users as follows:

server.get('/usersList', function(req, res) {
    var users = {};

    User.find({}, function (err, user) {
        users[user._id] = user;
    });

    res.send(users);
});

Of course, res.send(users); is going to send {}, which is not what I want. Is there a find alternative with slightly different semantics, where I could do the following?

server.get('/usersList', function(req, res) {    
    User.find({}, function (err, users) {
        res.send(users);
    });
});

Essentially, I want the callback to be executed only when all the users have been fetched from the database.

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.

This is just an Improvement of @soulcheck 's answer, and fix of the typo in forEach (missing closing bracket);

server.get('/usersList', function(req, res) {
    User.find({}, function(err, users) {
        res.send(users.reduce(function(userMap, item) {
            userMap[item.id] = item;
            return userMap;
        }, {}));
    });
});

cheers!

app.get('/users', function(req,res,next) {
  User.find().exec(function(err, users){
     res.send(users);
  });
};

http://mongoosejs.com/docs/queries.html