在猫鼬中通过updateOne预钩子更新阴影字段?

时间:2020-07-29 14:25:04

标签: javascript node.js mongodb 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
    },
});

顺便说一句,我可以确认挂钩已被调用,但该字段未更新。

1 个答案:

答案 0 :(得分:0)

事实证明,您不能直接访问字段值,而需要在查询中利用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();
});