I'm trying to get a value from mongoose and add it to the schema document by using virtual method and virtual field as like follows,
const sourceSchema = require('../source/schema.js').schema;
var Source = mongoose.model('Source', sourceSchema);
const schema = new Schema({
sourceId: {
type: Schema.Types.ObjectId,
required: true
},
description: {
type: String,
required: true
},
resources: {
type: Object
},
createdDate: {
type: Date
}
}
},
{
versionKey: false,
virtuals: true
});
schema.virtual('displayName').get(function () {
return this.getDisplayName();
});
schema.method('getDisplayName', async function () {
var source = await Source.findById(this.id);
if(source) {
var displaySource = JSON.parse(source['data']);
console.log(displaySource['displayName']);
return displaySource['displayName'];
}
});
But it's always coming as empty whereas it's printing the value in console, it never waits for the execution to complete. I'm not sure why it's not waiting for the execution while I'm using await.
Any help on this would be greatly helpful and much appreciated.
from Mongoose schema virual and async await
No comments:
Post a Comment