I have following schema:
// foo.js
...
const fooSchema = new Schema(
{
name: {
type: String
}
},
{
toJSON: {
virtuals: true
},
toObject: {
virtual: true
}
}
);
// sample virtual
fooSchema.virtual('sampleVirtual').get(function () {
return 'I am a virtual'
});
export default mongoose.model( 'foo', fooSchema );
and another schema where I have a ref on the above schema:
// hello.js
...
const helloWorldSchema = new Schema(
{
name: {
type: String,
required: true
},
myFoo: {
type: mongoose.Types.ObjectId,
ref: 'foo'
}
},
{
toJSON: {
virtuals: true
},
toObject: {
virtual: true
}
}
);
export default mongoose.model( 'HelloWorld', helloWorldSchema );
I am now using Mongoose' findOne() method to query for a document of the helloWorldSchema collection and want to populate the myFoo document with it's virtual sampleVirtual:
// get.js
const retVal = await helloWorldModel
.findOne({_id: <some-id> })
.populate({ path: 'myFoo', select: '_id name sampleVirtual' })
.exec();
console.log(retVal.myFoo.sampleVirtual) //undefined
Am I doing something wrong?
Best Valentin
Your code has some typos. The
toJSONandtoObjectare schema options, and theoptionsis the second parameter of themongoose.Schemaclass constructor. Themongoose.Schemaclass constructor signature is:E.g. ("mongoose": "^7.3.1")
Debug logs:
The virtual field
sampleVirtualis there.