Home > Software design >  How to update a child in an array in mongodb collection using mongoose?
How to update a child in an array in mongodb collection using mongoose?

Time:12-26

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
  }
...

CodePudding user response:

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

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

Working example

  • Related