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