1

I have the following MongoDB model:

const Relation = mongoose.model('Relation',{
 name :{
 type: String,
 },
 port:{
 type: Number,
 }, 
 services: { type : Array , "default" : [] }
});

Each port is a unique number for each document. A collection could have the following values:

{
 "port":"116", //unique number
 "name":"xzy",
 services: [
 {"id":'1', "trust":"good"},
 {"id":'2', "trust":"bad"},
 ]
}

How can for example make the "trust" value "bad" for the object with the "id"= 1 ??

I assume I should first find the collection that matchs the port number "116" and then find the object inside the Services array that has the "id" of 1. How can I do that in mongoose?

asked Feb 14, 2019 at 10:02

1 Answer 1

2

You can use $ positional operator to update value inside an array

Relation.findOneAndUpdate(
 { "port": "116", "services.id": "1" },
 { "$set": { "services.$.trust": "bad" }}
)
answered Feb 14, 2019 at 11:10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.