简体   繁体   中英

How to push to deeply nested array in mongoose?

I have this Model:

        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)

I can post it to mongo successfully aswell as push to the received and send arrays / documents with the following code:

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))

however I cannot do something like:

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

how do I achieve the desired result by pushing a new object to the messages array inside the received array?

Try this:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM