【问题标题】:async/await not working with mongoose instance methodsasync/await 不适用于 mongoose 实例方法
【发布时间】:2020-03-26 18:50:24
【问题描述】:

我正在尝试创建需要存储路径的用户 mongoose 文档。我想等待创建目录并解析路径。但它不起作用,保存用户后,user.storagePath 仍然未定义。请找出问题。

下面是createStorage()的代码

const getMountRoot = require('../configuration/configuration').getMountRoot
const path = require('path')
const fs = require('fs')
const Logger = require('../configuration/configuration').getLogger

module.exports = (email, firstName, secondName) => {
  email = String(email).toLowerCase().replace(/[@_\.\-]/g, '')
  firstName = String(firstName).toLowerCase().replace(/[@_\.\-]/g, '')
  secondName = String(secondName).toLowerCase().replace(/[@_\.\-]/g, '')

  let storagePath = path.join(getMountRoot(), `${secondName}${email}${firstName}`)
  return fs.promises.mkdir(storagePath, { recursive: true })
    .then(() => { return storagePath })
    .catch(() => {Logger.log(err); return storagePath})
}

下面是实例方法

const createStorage = require('../extra/create-storage')

userSchema.methods.createStorage = async function() {
  this.storagePath = await createStorage(this.email, this.firstName, this.secondName)
}

请注意,在调用save() 之前,我先在User 实例上调用createStorage()

【问题讨论】:

  • 在模型实例上调用await createStorage 时是否调用它?查看代码会有所帮助。
  • @qqilihq 不,我没有这样做,有帮助吗?
  • @qqilihq 调用实例方法时等待,你能解释一下为什么我需要这样做吗?例如,如果它在多个函数调用中出现故障,那么我是否需要等待像这个实例这样的较低调用或所有导致 createStorage() 的调用?
  • 是的,基本上你需要“一直等待”。或者,您可以将 save() 移动到实例方法中并将其命名为 createStorageAndSave 之类的名称,或者改用 pre 钩子之一。

标签: node.js mongoose async-await mongoose-schema


【解决方案1】:

正如@qqilihq 所想,我需要等待实例方法调用。这样做是正确的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2019-10-24
    • 2018-07-10
    • 2023-03-16
    • 2021-06-18
    • 2019-05-30
    • 2021-05-10
    相关资源
    最近更新 更多