【问题标题】:How to push to deeply nested array in mongoose?如何在猫鼬中推送到深度嵌套的数组?
【发布时间】:2021-07-26 07:03:02
【问题描述】:

我有这个模型:

        const MessagesSchema = mongoose.Schema({ //for individual message
        text: {
            type: String,
            required: true
        }
    }, { timestamps : true })
    
    const MessagesCollectionSchema = mongoose.Schema({ //for received and sent
        _id: {
            type: String,
            required: true
        }, 
        username: {
            type: String,
            required: true
        }, 
        messages: [MessagesSchema]
    }, { timestamps : true })
    
    const UserInboxSchema = mongoose.Schema({ //wrapper around all chats
        _id: {
            type: String,
            required: true
        },
        received: [MessagesCollectionSchema],
        sent: [MessagesCollectionSchema]
    })
   const MessageInbox = mongoose.model('message', UserInboxSchema)

我可以将它成功发布到 mongo 以及使用以下代码推送到接收和发送的数组/文档:

MessageInbox.findById(req.params.id) .then ( record => {
    const userid = req.body.id
    record.received.push({ _id: userid, username: 'Gamezz', messages: [{ text: 'again!!'}]})
    record.save().then ( result => res.send( result ))
                 .catch( err => res.send( err ))
}) .catch ( err => res.send(err))

但是我不能这样做:

record.received.user.messages.push({ text: 'new message' })

如何通过将新对象推送到接收数组中的消息数组来获得所需的结果?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:

    试试这个:

    MessageInbox.findByIdAndUpdate(req.params.id,{
      $push: { received: {
          _id: userid,
          username: 'Gamezz',
          messages: [{ text: 'again!!'}]
      }}
    }, {new: true}).then(response => {
        res.send(response)
    }).catch(err => res.send(error));
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 2016-06-05
      • 2015-02-09
      • 1970-01-01
      • 2016-01-29
      • 2019-10-13
      • 1970-01-01
      • 2021-04-18
      • 2019-11-15
      相关资源
      最近更新 更多