Home > Back-end >  Why mongoose populate works but virtual populate doesn't?
Why mongoose populate works but virtual populate doesn't?

Time:09-09

I have the following schema as per the docs:

const toolRecordSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId },
});

toolRecordSchema.virtual("user", {
  ref: "User",
  localField: "userId",
  foreignField: "_id",
  justOne: true,
})

And when I'm populating the virtual nothing happens:

db.ToolRecord.find().populate("user")

However if I add "ref" to the userId in the schema, and do .populate("userId"), it works as expected, meaning the problem isn't with the relation between the models but rather in the virtual population.

Any ideas What I'm doing wrong?

if I add mongoose.set("debug", true), I can see that adding the .populate("user") to the query products this output in mongoose debug logs:

users.find({}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})

and adding the .populate("userId") (which works) products this log:

users.find({ _id: { '$in': [ new ObjectId("631a1fe960d1f82c7fa51a06") ], [Symbol(mongoose#trustedSymbol)]: true }}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})

so we can see where the problem lies. Question is why is that virtual population doesn't work?

I'm running mongoose 6

CodePudding user response:

You need to add virtuals: true option on the toJSON and toObject() options.

const toolRecordSchema = new mongoose.Schema(
  {
    userId: { type: mongoose.Schema.Types.ObjectId },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

CodePudding user response:

You add in the model file this code. Add this code end of the database model code.

{
toJSON: { virtuals: true },
toObject: { virtuals: true }}
  • Related