【问题标题】:How could i populate document after .save function with pre hook.save 函数后如何使用 pre hook 填充文档
【发布时间】:2019-09-10 23:29:32
【问题描述】:

我有预挂钩来填充设置为schema.pre(/^find/, fn) 的所需字段。现在我正在尝试让相同类型的系统与document.save() 函数一起使用,遗憾的是它既不适用于schema.pre('save'),也不适用于schema.post('save')

所以,这会很好地填充字段:

let user = await User.findOneAndUpdate({_id: user._id}, {$set: {testFieldWithRef: someObjectId}}, {new: true});
console.log(user.testFieldWithRef) //would output populated field instead of objectId

那个不会用我的 .pre 钩子填充字段

let user = await User.findOne({_id: user._id})
user.testFieldWithRef = someObjectId
user.markModified('testFieldWithRef')
user = await user.save()
console.log(user.testFieldWithRef) //would output someObjectId

【问题讨论】:

    标签: node.js mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    所以,这已经奏效了。遗憾的是,mongoose 在 stackoverflow 上并不受欢迎

    schema.pre('save', async function(next) {
        await this.populate({
            path: 'testFieldWithRef'
        }).execPopulate();
        next()
    })
    

    【讨论】:

    • 好兄弟?
    猜你喜欢
    • 2021-01-08
    • 2015-03-27
    • 2014-03-22
    • 2022-10-23
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2021-05-17
    • 2012-02-06
    相关资源
    最近更新 更多