首页 > 解决方案 > Mongoose:如何在保存之前手动设置_id?

问题描述

给出以下代码:

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?

为什么 this.name 未定义

标签: node.jsmongoosemongoose-schema

解决方案


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

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

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

推荐阅读