I'm using asynchronous virtual properties to count how often that document has been referenced in a specific other collection. This feature has been added.
// Schema mortician.js
const Pickup = require('./pickup')
const mongoose = require('mongoose')
const mortSchema = mongoose.Schema({
name: {
type: String,
required: true
}
}, { timestamps: true })
mortSchema.virtual('count').get( async function () {
return await Pickup.countDocuments({ mortician: this._id })
})
module.exports = mongoose.model('Mortician', mortSchema)
However, when I try to render it like this, it's returning a Promise: Promise { <pending> } and the displayed value is [object Promise], like joseym describes over here: Support for Asynchronous Virtual #1894
async index(req, res) {
try {
const morticians = await Mortician.find({}).exec()
res.render('pages/morticians', {
title: 'Bestatter',
page: req.originalUrl,
morticians: morticians
})
} catch (err) { err => console.log(err) }
..
}
Since I'm directly passing the morticians element to render, I've idea where to place the needed await for mortician.count. I want to avoid looping (for (const mortician of morticians)), before passing it to res.render. How to solve this?
Does it even make sense, to query ("OtherSchema".find..) with in an virtual property? What's best practice?