您可以在find()之后更新then()回调中返回的行吗?

时间:2019-01-07 04:30:26

标签: node.js mongodb express mongoose

我需要通过用户名在数据库中找到用户行,然后使用该用户名在请求表中查找它的朋友请求,然后:

  • 更新请求以防止重复请求

  • 将通知消息添加到用户的通知数组

  • 通过所在行的套接字ID向用户发送

您可以在then()中更新mongo行吗?

我在回调中尝试了此操作

requester.update({ $push: { 'notifications': {'msg': msg, 'type': type} } });

这是上下文:

      User.find({'username': requester}).exec()
      .then(requester => {
          Request.findOneAndUpdate({'requester': requester[0]._id, 'requestee': requestee.user._id}, {'status': 1}).then(function(){
              const msg = requestee.user.username + ' accepted your friend request ',
                    type = 1;
              requester.update({ $push: { 'notifications': {'msg': msg, 'type': type} } });
              app.io.to(requester[0].socket).emit({'msg': msg, 'type': type});
          });
      })
      .catch(err => { 
         console.log(err);
      });

我当前得到: TypeError:requester.update不是函数

1 个答案:

答案 0 :(得分:0)

您可以随后更新mongodb结果。如果使用$push,则应调用模型而不是模型的结果。

 User.update({ _id: 1 }, { $push: { 'notifications': {'msg': msg, 'type': type} } });

这显然不起作用,因为requester只是User.find()中的JavaScript对象

旁注:如果您只想找到一个用户,请使用findOne而不是findfind将返回数组,而findOne将返回对象