Answer the question
In order to leave comments, you need to log in
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' },
],
},]
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 questionAsk a Question
731 491 924 answers to any question