0

I'm just wondering how I can update a nested array field inside a mongo db document.

Here is how my schema looks like:

const userSchema = new Schema({
  email: {type: String, unique: true, lowercase: true},
  password: String,
  firstName: String,
  lastName : String,
  role: String,
  children: Array
});

This is how the document looks like:

{
"_id" : ObjectId("5b3570f3150a0b57a4e7421e"),
"children" : [ 
    {
        "fullName" : "John doe",
        "yearGroup" : "4",
        "absences" : [],
        "id" : "765"
    }
],
"email" : "[email protected]",
"firstName" : "John",
"lastName" : "Doe",
"role" : "parent",
"__v" : 1

}

Where I want to push a new object into to 'absences' array.

1 Answer 1

1

to do this you have to use the mongodb $push operator via the update operation, which i guess that is what you want to do, but you did not specify your match query. To push to absences do this ( i assume the match query is children.fullName )

db.ops.update( { "children.fullName": "John doe" } , { $push: { "children.$.absences": "data to push" } } );

the $ placeholder tells mongodb to replace it self ( i.e $ ) with the matched array index.

incase you want to prevent duplicate elements in absences field you have to use the $addToSet operator

db.ops.update( { "children.fullName": "John doe" } , { $addToSet: { "children.$.absences": "data to push" } } );
Sign up to request clarification or add additional context in comments.

1 Comment

I get an error ''cannot use the part (children of children.id) to traverse the element'

Your Answer

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.