jeyremd
jeyremd

Reputation: 199

mongoose update a object inside a array of objects

I'm trying to add an object in a specific object inside an array of objects.

My model:

[
    {
        "_id": "634c0777427df2a5adc17b4c",
        "title": "PROGRAMME TEST",
        "user": {
            "name": "Jérémy",
            "email": "[email protected]",
            "profilPicture": "google.fr"
        },
        "exercices": [
            {
                "exercice": "6349563c2e0df123096b7feb",
                "totalSet": 1,
                "rest": "1"
                // add value here 
            },
            {
                "exercice": "634956452e0df123096b7fed",
                "totalSet": 2,
                "rest": "2"
            }
        ]
    }
]

Here is my query. It does nothing (not even an error):

return this.programModel.findOneAndUpdate(
  {
    $and: [
      {_id: '634c0777427df2a5adc17b4c' }, (program id)
      { exercices: { 'exercices.exercice': "6349563c2e0df123096b7feb" } }, (exercice id want I to add my object)
    ]
  },
  { $push: {"exercices.exercice": {result: result}}},
  { new: true }
);

EDIT:

Here is my entire program.entity.ts in case it can help.

unfortunately, none of the answers in the comment did work.

As I'm not familiar with mongoose and nestJS, Might I did a mistake in my entity?

export type ProgramDocument = Program & Document

class Exercices {
  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Exercice' })
  exercice: Exercice

  // others @Prop
  
  @Prop({ type: mongoose.Schema.Types.Array})
  result: Array<ExerciceResult>
}

class ExerciceResult {
  @Prop()
  set: number;

  @Prop()
  kilogram: string;
}


@Schema()
export class Program {
  // others @Prop

  @Prop({ type: mongoose.Schema.Types.Array})
  exercices: Array<Exercices>

}

export const ProgramSchema = SchemaFactory.createForClass(Program)

Upvotes: 1

Views: 129

Answers (1)

turivishal
turivishal

Reputation: 36154

Just need to correct an update part,

  • $ references the object that matches in the subdocument condition/query, so it would be "exercices.$.result"
let result = { set: 1, kilogram: "10" };

return this.programModel.findOneAndUpdate(
  {
    _id: "634c0777427df2a5adc17b4c",
    "exercices.exercice": "6349563c2e0df123096b7feb"
  },
  {
    $push: {
      "exercices.$.result": result
    }
  },
  { new: true }
);

Playground

Upvotes: 2

Related Questions