【问题标题】:Updating a shadow field, via updateOne pre hook, in mongoose?在猫鼬中通过 updateOne 预挂钩更新影子字段?
【发布时间】:2023-03-09 13:36:01
【问题描述】:

谁能解释如何在 mongoose (5.9.5) 中使用 updateOne 预挂钩?

我需要创建一个规范化的“影子字段”(不确定正确的术语)以帮助进行某些搜索。虽然我可以在保存过程中更新阴影场,但在更新过程中遇到了问题。

保存预挂钩:

personSchema.pre('save', function (next) {
    if (this.isModified('name')) {
        const name = this.name;
        if (name && name.trim().length > 0) {
            const shadowName = name.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
            this.shadowName = shadowName.toLowerCase();
        } else {;
            this.shadowName = name;
        }
    }

    // do stuff
    next();
});

updateOne 执行等效操作似乎不起作用(shadowName 保持初始保存时给出的值):

personSchema.pre('updateOne', function (next) {
    const name = this.name;
    if (name && name.trim().length > 0) {
        const shadowName = name.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
        this.update({}, { shadowName: shadowName.toLowerCase() });
    } else {
        this.shadowName = name;
    }

    // do stuff
    next();
});

架构:

const personSchema = new mongoose.Schema({
    resourceId: {
        type: String,
        required: true,
        unique: true,
        index: true,
        uppercase: true
    },
    name:{
        type: String,
        required:true,
        index: true
    },
    // can be used for searches, but don't update directly
    shadowName: {
        type: String,
        index: true
    },
});

顺便说一句,我可以确认调用了钩子,但该字段没有更新。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    事实证明,您不能直接访问字段值,而是需要在查询中利用 get()set() 方法。

    将 pre-updateOne 挂钩更改为以下工作:

    personSchema.pre('updateOne', function (next) {
        const name = this.get('name');
        if (name && name.trim().length > 0) {
            const shadowName = name.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
            this.set('shadowName', shadowName.toLowerCase());
        } else {
            this.set('shadowName', name);
        }
    
        // do stuff
        next();
    });
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 2018-08-26
      相关资源
      最近更新 更多