简体   繁体   中英

How to update a child in an array in mongodb collection using mongoose?

I am a very beginner with mongodb/mongoose. I have this mongoose document:

const MySchema = mongoose.Schema({
  name: {
    type: String,
    minLength: 5,
    maxlength: 100,
    required: true
  },
  children: [{
    name: {
      type: String,
      minLength: 10,
      maxlength: 200,
      required: true
    },
  }],
}],

that saves a document like this:

 {
  "_id" : ObjectId("63a4bde8680e26987e8abd1f"),
  "name" : "parent 1",
  "children" : [{
      "name" : "child 1",
      "_id" : ObjectId("63a94a4a1baa3d5bfdc22fb4")
    },
    {
      "name" : "child 2",
      "_id" : ObjectId("63a94a4a1baa3d5bfdc22fb4")
    }
  ]
}

how can I update a single child given the objectId (ex: 63a94a4a1baa3d5bfdc22fb4) using mongoose?

I recall the parent but I don't kbnow how to update a single child element

let parent = await Manager.getParent(parentId);
  let documentToUpdate = {
    question: question,
    questionType: questionType,
    answers: answers
  }
...

You can do it with positional operator - $ , like this:

MyModel.updateOne({
  "name": "parent 1",
  "children._id": "63a94a4a1baa3d5bfdc22fb4"
},
{
  "$set": {
    "children.$.name": "new name"
  }
})

Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM