猫鼬:如何在保存之前手动设置_id?

时间:2019-04-04 19:29:17

标签: node.js mongoose mongoose-schema

给出以下代码:

const schema = new Schema({
    _id: {
        type: String
    },
    name: {
        type: String,
        required: true,
        trim: true
    }
}

schema.pre('validate', (next) => {
    console.log(this.name);
    this._id = crypto.createHash('md5').update(this.name).digest("hex");
    next();
});

const myObject = new MyObject({ name: 'SomeName' });
myObject.save();

应用程序抛出此错误消息:

MongooseError: document must have an _id before saving

我的问题是,如何为模型手动设置_id?

为什么此名称未定义

1 个答案:

答案 0 :(得分:2)

(next) => ...是箭头函数,其中this是词法,是指封闭范围,在Node.js模块范围中是module.exports

为了在函数内部获得动态this,它应该是常规函数:

schema.pre('validate', function (next) { ... })