Mongoose schema virual and async await
Getters and Setters cannot be async, that's just the nature of JS.
You never called callback
schema.method('getDisplayName', async function (cb) { // <-- added callback var source = await Source.findById(this.id); if(source) { var displaySource = JSON.parse(source['data']); console.log(displaySource['displayName']); cb(displaySource['displayName']) // <-- called callback } else cb(null)});
Then somewhere in code
Schema.findOne(function (err, schema) { schema.getDisplayName(function (displayName) { // got it here })})
Note that schema.virtual('displayName')
is removed
I defined displayName
as:
schema.virtual("displayName").get(async function () { const souce = await Source.findById(this.id); if (source) { return source.displayName; } return undefined;});
The property must have await
before referencing it, like this:
const name = await sourceDoc.displayName;
as the property is an async function elsewhere. If somebody can teach me how to call an async function without await
I'd be very happy.