Home > database >  How can i combine a result from $elemMatch and push in MongoDb
How can i combine a result from $elemMatch and push in MongoDb

Time:06-21

I have a problem.

This is my code:

How i structure the chats field in my mongoose schema:

chats: [
    {
        id: Number
        messages: [{text: String}]
    }
]

The code with the problem:

const u = await users.findByIdAndUpdate(req.user._id, {
    chats: {$elemMatch: {id: req.params.id}}
})

I want to find a chat with the id i get from params, and then i want to push into the cat i found a new message into the messages field. i am not sure how i can do this.

Someone can help me pls?

Thank You ❤.

CodePudding user response:

You can use .$[<identifier>] for this. For example, {text: 'newMessages'} into chat id: 23452

db.collection.update(
{},
{$push: {"chats.$[c].messages": {text: 'newMessages'}}},
{arrayFilters: [{"c.id": 23452}]}
)

See how it works on the playground example

  • Related