Mongoose:获取完整的用户列表 [英] Mongoose: Get full list of users
问题描述
我尝试使用 Mongoose 发送所有用户的列表如下:
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);
});
当然,res.send(users);
是要发送{}
,这不是我想要的.是否有语义略有不同的 find
替代方案,我可以在其中执行以下操作?
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.
推荐答案
好吧,如果你真的想返回一个从 _id
到 user
的映射,你总是可以这样做:
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()
返回数组中所有匹配的文档,因此您最后剪下的代码将该数组发送给客户端.
find()
returns all matching documents in an array, so your last code snipped sends that array to the client.
这篇关于Mongoose:获取完整的用户列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!