I'm trying to add a object in a specific object inside a 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, I may 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)
CodePudding user response:
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 }
);