【问题标题】:MongodDB Mongoose Collection.findAndModify Upsert: tureMongodB Mongoose Collection.findAndModify Upsert: true
【发布时间】:2016-10-08 09:48:09
【问题描述】:

我正在尝试为 NodeJS、Express、MongoDB 应用程序的用户添加基本的用户对用户消息传递服务。

我有两个用于该功能的 MongoDB 文档:一个包含每个单独消息的“消息”文档和一个“对话”文档,它将引用属于它的所有“消息”。

因此,一旦消息到达服务器,我想对属于发件人和收件人的对话执行 findAndModify。如果存在这样的对话,则使用新消息对其进行更新。如果对话不存在,则创建它,然后添加消息。

app.post('/messages', function(req, res){
  var message = { // Create an object with the message data
    sender: req.body.sender,
    recipient: req.body.recipient,
    messageContent: req.body.msgCont,
    timeSent: Date.now()
  };
  Message.create(message, function(err, newMessage){ // Add the message to MongoDB
    if(err){
      console.log('Error Creating Message' + Err);
    } else {
      console.log("The New Message " + newMessage)
      Conversation.findOneAndUpdate({ // Find a conversation with both the sender
        $and: [                       // and receiver as participants (there should
        {$or: [                       // only ever by one such conversatoin)
          {"participants.user1.id" : req.body.sender},
          {"participants.user1.id" : req.body.recipient}
        ]},
        {$or: [
          {"participants.user2.id" : req.body.sender},
          {"participants.user2.id" : req.body.recipient}
        ]},
      ]}, {$setOnInsert : {
                            messages : message, 
                            "participants.user1.id" : req.body.sender,
                            "participants.user2.id" : req.body.recipient
                          },
      new : true,
      upsert : true
    }, function(err, convo){
        if(err){
          console.log(err + 'error finding conversation')
        } else {
          console.log("Convo " + convo)
        }
      });
    }
  });
  res.redirect('/matches');
});

将消息添加到数据库可以正常工作,但会话查询的某些内容不起作用。我得到了一个Convo null 的console.log,所以它没有返回错误,但对话中没有任何内容。

如果有人能看出我哪里出错了,我会非常高兴得到一些指导!

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    MongoDB findOneAndUpdate 方法 (documentation) 没有选项 new,而是 returnNewDocument。此外,您在这些选项中缺少大括号

    {
      returnNewDocument: true,
      upsert: true
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 2018-04-07
      • 2022-12-04
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 2017-08-23
      • 2013-05-04
      相关资源
      最近更新 更多