O
O
olezhenka2017-04-12 14:04:42
JavaScript
olezhenka, 2017-04-12 14:04:42

How to work with arrays in mongoose?

how to create a schema with an array and then update the array?
I wrote like this, it seems like I can get it, but how can I update it?
6bf2b8d2051c48c49606b7a0640e2427.PNG
xo.update gives error

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2017-04-12
@AppFA

There are a couple of options
. We get the document we need, update - save
1:

const xo = await XO.findById(id);
xo.board.push(10);
await xo.save();

Using $push
2:
await XO.update({ _id: id }, { $push: { board: 10 } })

E
emp1re, 2017-04-12
@emp1re

Through update, it is possible, as written above, through $push, but as we know, it only adds a new element to the array,
It is also possible through { $set: { "array.$.value" : "" } } but for this you need to make an exact selection to example -

db.board.update({"array.value" : "5"), { $set: {"array.$.value": "15"} })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question