解析猫鼬虚拟财产的承诺?

编程入门 行业动态 更新时间:2024-10-08 20:29:35

解析猫鼬虚拟<a href=https://www.elefans.com/category/jswz/34/1746891.html style=财产的承诺?"/>

解析猫鼬虚拟财产的承诺?

我正在使用异步虚拟属性来计算在其他特定集合中引用该文档的频率。 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 #1894

async index(req, res) {
  try {
    await Mortician.find({}, (err, morticians) => {
      console.log(morticians[0].count)
      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)。该如何解决?

用虚拟属性查询("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)
  }
}

更多推荐

解析猫鼬虚拟财产的承诺?

本文发布于:2024-05-07 13:15:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756407.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:财产

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!