Home > other >  Mongoose: Pushing values to an array inside a nested object
Mongoose: Pushing values to an array inside a nested object

Time:03-11

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' ]

CodePudding user response:

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" }]
  • Related