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

Mongoose: How to set _id manually before saving?

给出以下代码:

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 未定义

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

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

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