J
J
jedifa2021-07-28 20:54:45
Node.js
jedifa, 2021-07-28 20:54:45

How to update value in Mongodb array?

Please tell me, in the mongodb database there is a field answers which is an array, how can I increment the likes value in the answer array object and store it in the database?

_id:61016b11f857db0f456ee992
views:0
answers: [
{answer: "answer", username: "username", likes: 0}
]
question:
"question"
tags:"tag"
description:"descr"
owner:"61013f32532a47ffd53721bf"
__v:0


I tried doing like this:
answers.map(item => item.likes + 1);
 Model.save()

But it didn't work out

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuriy Vorobyov, 2021-07-28
@YuriyVorobyov1333

You have to use $set and $inc
You will get something like:

Model.update({}, {'$set': {
    {$inc: {
      `answers.$.likes`: 1 
    }},
}});

G
Gennady S, 2021-07-28
@gscraft

https://docs.mongodb.com/drivers/node/fundamentals... - there is an intelligible example, you need to request the element you are looking for { "answers.username": "username" } (the element you are looking for in the array must be uniquely identified, of course), but unlike the example, use the increment https://docs.mongodb.com/manual/reference/operator... - $set: { $inc: { likes: 1 } }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question