最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 10浏览 0评论

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

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

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

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

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论