Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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.

2 Answers

0 votes
by (106k points)

To get the full list of users in mongoose you can use the below-mentioned code:-

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.

0 votes
by (108k points)

If you'd like to send the data to a view pass then refer the following commands.

    server.get('/usersList', function(req, res) {

        User.find({}, function(err, users) {

           res.render('/usersList', {users: users});

        });

    });

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jan 5, 2020 in Web Technology by ashely (50.2k points)

Browse Categories

...