Home > OS >  Use 'virtual' in an array of objects (Mongoose)
Use 'virtual' in an array of objects (Mongoose)

Time:06-07

I have two schemas as the following:

const castListSchema = new Schema({
  id: String,
  roleInVideo: String
});

const videoSchema = new Schame({
  castList: { type: [castListSchema], default: [] }
});

I want to get data by the following structure:

castList: [
  {
    details: { ... },
    roleInVideo: 'director'

  },
  ...
]

I want to use virtual not aggregate and etc...

Is it possible? How?

CodePudding user response:

Yes, you can use the virtual function inside the array of objects.

Use the following code to use the virtual function for the array of objects.

videoSchema.virtual("castList.castData", {
  ref: "new_assets",
  localField: "castList.castListSchema",
  foreignField: "_id",
  justOne: true
});

In populate also use this "castList.castData" as key to retrieve the data.

  • Related