我正在使用异步虚拟属性来计算在特定的其他集合中引用该文档的频率。 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)
但是,当我尝试像这样渲染它时,它会返回一个 Promise:
Promise { <pending> }
显示值为[object Promise]
,就像 joseym 在这里描述的那样:Support for Asynchronous Virtual #1894async 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) }
..
}
由于我直接传递 morticians 元素进行渲染,因此我知道在哪里放置所需的
await
为 mortician.count
.在将其传递给 for (const mortician of morticians)
之前,我想避免循环( res.render
) .如何解决这个问题?在虚拟属性(property)中查询(
"OtherSchema".find..
)是否有意义?什么是最佳实践?
最佳答案
您需要执行您的 promise ,然后将结果保存在一个变量中,该变量将用于呈现它
像这样的东西
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)
}
}
关于javascript - 解决 Mongoose 虚拟属性(property)中的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61771396/