H
H
Horus1232020-09-02 13:32:56
MongoDB
Horus123, 2020-09-02 13:32:56

How to replace array element in mongoDB?

Have mongodb collection
5f4f747779ce6594351876.png

How to replace tablesState with updated one? Now I have another object created in the array, but the old one is not deleted.

const { email, tablesState } = req.body
            Users.update({ email }, { $set: tablesState }
                , function (err, WriteResult) {
                    if (err) return handleError(err);
                    res.status(201).json(WriteResult)
                }
            )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2020-09-02
@hzzzzl

so replace the array element, or the whole tablesState array?

User.updateOne(
    // нужен айдишник для элемента, чтобы его выбрать из базы
  { email: email, 'tablesState._id': table_id },   
    // тогда можно будет так
  { $set: { 'tablesState.$' : tablesStateElement } }  
)

A
Alexander Cheremkhin, 2020-09-11
@Che603000

const { email, tablesState } = req.body
            Users.findOne({ email })
               .then(doc=>{
                    doc.tableState = tableState;
                    return doc.save();
                })
                .then(doc=>res.json(doc))
                .catch(err=>handlerError(err);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question