node.js - async/await 不适用于 mongoose 实例方法

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

我尝试创建需要存储路径的用户 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()

最佳答案

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

关于node.js - async/await 不适用于 mongoose 实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134160/

相关文章:

javascript - 在 JavaScript 中实现协程控制流

javascript - ipcMain.handle 内的 fs.readdir 不返回

node.js - 将 S3 对象的内容流式传输到哈希算法 node.js

javascript - Mongoose .env 返回未定义

node.js - 如何从结果中删除 mongo 特定字段(NodeJS、Mongoose)

c# - 任务异步/等待不适用于 WPF,因为它在其他场景中有效

javascript - 如何在ejs模板中显示json数据?

node.js - 将 Firebase 的第三方用户数据对象发布到服务器

node.js - 我在连接 mongodb 和express 时遇到错误,我的终端疯了

c# - 异步等待 : is the main thread suspended?