arrays - es6 Mongoose 嵌套findById promise

标签 arrays node.js mongoose ecmascript-6

我正在使用node express mongoose/mongo等构建一个restful api。我正在尝试输出特定用户正在关注的一组用户。这是架构。

var UserSchema = new mongoose.Schema({
  username: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/^[a-zA-Z0-9]+$/, 'is invalid'], index: true},
  email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
  bio: String,
  image: String,
  following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
}, {timestamps: true});

因此,每个用户在键“following”的数组中都有用户数组。我试图输出该列表,首先通过用户自己的 id 查找用户记录,然后通过该数组进行映射以查找当前用户的关注用户。

router.get('/users/friends', auth.required, function(req, res, next) {
  var limit = 20;
  var offset = 0;

  if(typeof req.query.limit !== 'undefined'){
    limit = req.query.limit;
  }

  if(typeof req.query.offset !== 'undefined'){
    offset = req.query.offset;
  }

  User.findById(req.payload.id)
  .then(function(user){
    if (!user) { return res.sendStatus(401); }

    return res.json({
      users: user.following.map(function(username){
        User.findById(username)
          .then(function(userlist){
            console.log('userlist:',userlist.username);
            return userlist.username;
          })
          .catch(next)
      })
    })
  })
  .catch(next);
});

现在,这段代码中的console.log在js控制台中输出了正确的数据,但我似乎找不到将其传递给客户端的方法。到目前为止,我的努力在客户端中带来了“空”值。正确的记录数量,但只是空值。有什么想法可以解决这个问题吗?

在听取下面的建议后,我将我的代码修改为这样。现在它成功地将第一条记录发送给客户端,但随后出现错误

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent. Blockquote

router.get('/users/friends', auth.required, function(req, res, next) {
    var limit = 20;
    var offset = 0;

    if (typeof req.query.limit !== 'undefined') {
        limit = req.query.limit;
    }

    if (typeof req.query.offset !== 'undefined') {
        offset = req.query.offset;
    }


    User.findById(req.payload.id)

        .then(function(user) {
            if (!user) {
                return res.sendStatus(401);
            }
            Promise.all(
                user.following
            ).then(function(userarray) {
              console.log(userarray);
                userarray.forEach(function(userid) {
                     Promise.all([
                        User.find({
                            _id: {
                                $in: userid
                            }
                        })
                        .limit(Number(limit))
                        .skip(Number(offset))
                        .populate('author')
                        .exec()
                    ]).then(function(results) {
                        userdetails = results[0];
                        var userdetailsCount = results[1];

                        return res.json({
                          userdetails: userdetails.map(function(userdetail){
                            return userdetail;
                          })
                        });
                    })
                })
            })
        })
        .catch(next);
});

最佳答案

您的问题部分是:

return res.json({
  users: user.following.map(function(username){
    User.findById(username)
      .then(function(userlist){
        console.log('userlist:',userlist.username);
        return userlist.username;
      })
      .catch(next)
  })
})

User.findById(username) 位将返回一个 promise 。但你并没有等待这个 promise 。我猜您认为遵循该 promise 的 then 函数将 userlist.username 记录到控制台并返回它,应该意味着您的 map 函数返回 userlist.username 的列表。但这种情况并非如此。您的 map 函数返回一个 Promise 数组。

您真正想要的是像 Bluebird 的 Promise.map 这样的功能:http://bluebirdjs.com/docs/api/promise.map.html (或者,在您碰巧使用的任何 Promise 库中寻找类似的功能来处理 Promise 数组)。

关于arrays - es6 Mongoose 嵌套findById promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969555/

相关文章:

javascript - 如何使具有 map 功能的 3 列网格使用react

javascript - 如何使用具有函数结果值的新属性来扩展集合中的每个对象

node.js - 如何将一组标准参数传递给 async.js 系列中的每个函数?

node.js - 如何知道电脑的RAM总量?

node.js - 如何保护 Mongoose/MongoDB 中的密码字段,以便在填充集合时它不会在查询中返回?

mongodb - 如何查询所有子文档

javascript - 格式化curl返回数据

iphone - 将数组发送到下一个 viewcontroller iOs xcode

node.js - 用户套接字与服务器断开连接后如何发送消息

node.js - 如何在 nodejs 中使用 mongodb 时间戳数据类型?