D
D
dimasik24na72021-03-30 11:50:52
Mongoose
dimasik24na7, 2021-03-30 11:50:52

MongoDB Express How to push an object in a nested array to a document found by query?

I am using mongoose.
There is a document:

{id: 1,
  name: 'John',
  surname: 'Doe',
  chats: [
  {
      type: 'user',
      chatId: 2,

      messages: [
        { isMy: false, text: 'Foo' },
        { isMy: true, text: 'Bar' },
      ],
    },
    {
      type: 'user',
      chatId: 3,

      messages: [
        { isMy: false, text: 'Bar' },
        { isMy: true, text: 'Foo' },
      ],
    },]


How can I find a user by id , then find a specific chat by chatId and add a new object to the messages

array My template:
app.post('/users/:userId/add_message', async (req, res) => {
        const userId = req.params.userId;
  const { chatId, message } = req.body;
userTable.findOneAndUpdate({ id: userId }, { $push: { 'chats[chatId].messages': message } });
})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question