V
V
Viktor2021-12-24 01:20:28
MongoDB
Viktor, 2021-12-24 01:20:28

How to update value in array of mongoDB object?

Hello. Help with a question on monga.
From the node I make a request to update the data, but I get a strange situation.
We have such an object.

_id: 61c4f31d0c7a0a29c238d5c8
firstName:  "NAME",
middleName:  "",
lastName:  "",
phoneNumbers:
    [
       {phoneNumber: "111111", phoneStatus:  false, defaultPhone: true, _id: 61c4f31d0c7a0a29c238d5c9},
       {phoneNumber: "2222", phoneStatus:  false, defaultPhone: true, _id: 61c4f31d0c7a0a29cdff4d5c9},
    ],
avaSrc: ""


I need to update phoneStatus where the phone number is 2222. When I try to do this, I get an object without the phoneNumber field, while the rest of the fields remain.

I get this look
[
       {phoneNumber: "111111", phoneStatus:  false, defaultPhone: true, _id: 61c4f31d0c7a0a29c238d5c9},
       {phoneStatus:  true, defaultPhone: true, _id: 61c4f31d0c7a0a29cdff4d5c9},
    ],


Here is an example request
await UserModel.findOneAndUpdate({
  phoneNumbers: { $elemMatch: { phoneNumber: "2222"} },
  }, {$set: { phoneNumbers: { phoneStatus:  true}
});


Tried to use updateOne, tried without $set, still deletes the phoneNumber field.

Help to make the right request.

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