Search code examples
javascriptnode.jsmongodbmongoosemongoose-populate

Why am I getting a StrictPopulateError when trying to populate a path from an array in my Mongoose schema?


how can I populate 'from and to' from messages array in this schema ?

const chatSchema = new Schema({
    POne: {type: Types.ObjectId, ref:'User', required: true},
    PTwo: {type: Types.ObjectId, ref:'User', required: true},
    messages:[{
      from:{type: Types.ObjectId, ref:'User', required: true},
      to:{type: Types.ObjectId, ref:'User', required: true},
      message: {type: String, required:true},
      date: {type: Date, default: Date.now}
    }]
}, {
    timestamps: true,
    toJSON: { virtuals: true }, 
    toObject: { virtuals: true },
})

this the end point I used

const chat = await chatModel.findOne({
        $or: [
            {POne: req.user._id, PTwo: destId},
            {POne: destId, PTwo: req.user._id},
        ]
    }).populate([{
        path:"POne"
    },{
        path: "PTwo"
    },{
        path:"from", options: {strictPopulate: false}
    },{
        path: "to", options: {strictPopulate: false}
    }]) 

even I did it turning off strictPopulate option and it doesn't work. I still get this error message

"StrictPopulateError: Cannot populate path from because it is not in your schema. Set the strictPopulate option to false to override."

how can I populate correctly a path from an array in Mongoose schema?


Solution

  • You should use nested populate:

    const chat = await chatModel
      .findOne({
        $or: [
          { POne: req.user._id, PTwo: destId },
          { POne: destId, PTwo: req.user._id },
        ],
      })
      .populate([
        {
          path: 'POne',
        },
        {
          path: 'PTwo',
        },
        {
          path: 'messages',
          populate: {
            path: 'from',
          },
        },
        {
          path: 'messages',
          populate: {
            path: 'to',
          },
        },
      ]);
    

    Also, you should define your schema references as Schema.Types.ObjectId:

    const chatSchema = new Schema({
        POne: {type: Schema.Types.ObjectId, ref:'User', required: true},
        PTwo: {type: Schema.Types.ObjectId, ref:'User', required: true},
        messages:[{
          from:{type: Schema.Types.ObjectId, ref:'User', required: true},
          to:{type: Schema.Types.ObjectId, ref:'User', required: true},
          message: {type: String, required:true},
          date: {type: Date, default: Date.now}
        }]
    }, {
        timestamps: true,
        toJSON: { virtuals: true }, 
        toObject: { virtuals: true },
    })