猫鼬:获取完整的用户列表 [英] Mongoose: Get full list of users

查看:85
本文介绍了猫鼬:获取完整的用户列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用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.

推荐答案

好吧,如果您真的想返回从_iduser的映射,则可以始终这样做:

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.

这篇关于猫鼬:获取完整的用户列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆