【问题标题】:Push new object to nested mongodb document where particular condition matches within a sub document将新对象推送到嵌套的 mongodb 文档,其中特定条件在子文档中匹配
【发布时间】:2019-03-27 00:30:06
【问题描述】:

我是 Nodejs 和 Mongodb 的新手。我正在我的项目中构建消息聊天功能。我已经完成了消息架构。

这是我的用户模型架构:

var UserSchema = new mongoose.Schema({

    name : {
       type     : String
    },
    email : {
       type : String
   },
   password : {
       type     : String
   },
   chats : [{
        chatId : String,
        messages : [{
            type  : mongoose.Schema.Types.ObjectId,
            ref   : 'Message'
        }]
    }]  
});

我想将所有新的消息对象添加到 chatId 匹配的子文档中。所以,我可以很容易地在前端(即 Angular)上使用它与结构化
我试过这个:

var msg = new Message({
    senderId : req.user._id,
    to       : toUser,
    from     : user,
    message  : req.body.msg,
    datetime : new Date()
})

msg.save();

const chatFr = await User.findOneAndUpdate(
        { 'chats.chatId' :  req.user._id },
        { $push : { 'chats' : msg  }}
)

它正在创建一个单独的对象。我不知道如何在此处的子文档中使用“where”。我来自 Sql 背景。请帮助如何在 mongodb/mongoose 的子文档中执行条件查询

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    试试这个:

    await User.findOneAndUpdate(
      { 'chats.chatId' :  req.user._id },
      { $addToSet: { 'chats.$.messages' : msg  }}}
    )
    

    您需要使用$ position operator 插入。您也可以使用$addToSet

    【讨论】:

    • 哇。非常感谢它与“$”位置运算符一起使用。我还将阅读有关 $addtoSet 运算符的信息...再次感谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2021-05-01
    • 2017-02-20
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多