I have been searching for an answer for this for hours – there seem to be some similar questions without a working answer – so if you can help me solve it then you can have my car, my house and my first born – whatever you want!
When I create a record for the model below, I need a way to insert values to the participants nested array:
const recordSchema = new Schema ( {record: [ { eventDate: Date, game: { type: Schema.Types.ObjectId ,ref: "Game" }, winner: { type: Schema.Types.ObjectId ,ref: "Member" }, particpants: [ { type: Schema.Types.ObjectId ,ref: "Member" } ] }, { timestamps: true, } ], } )
Creating a record works fine for all fields except participants, which remains unpopulated:
Record.create({record: { game: game, winner: winner, participants: participants }})
I have tried several methods to try to get to that nested array and (for example) update after creation, but so far I haven’t been able to get there. Keep in mind this needs to create programatically – I can’t hard code in any values.
Many, many, many thanks if you are able to help me with this.
Edit: adding the data being input as comment said this would be useful:
console logging the variables right before the create returns the following: game: ‘6220ca4d8179d6685b4c05b7’, winner: ‘6225ed9f21a3b31c86098b8d’, participants: [ ‘6225ec458e34373cf7337d68’, ‘6225ed9f21a3b31c86098b8d’ ]
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You have a typo in your schema, as you can see your schema expects particpants
but in your .create()
you are passing participants
.
You are missing an i
after c
in schema.
participants: [{ type: Schema.Types.ObjectId, ref: "Member" }]
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0