node.js - 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 未定义
解决方案
(next) => ...
是箭头函数,其中this
是词法,指的是封闭范围,它module.exports
位于 Node.js 模块范围内。
为了this
在函数内部获得动态,它应该是常规函数:
schema.pre('validate', function (next) { ... })
推荐阅读
- python - 当我写入与以前删除的文件具有相同文件名的文件时,scipy.io.wavfile.write 不起作用
- html - 为什么这个 CSS 代码让我的下拉菜单只显示 3 中的一项?
- javascript - 仅使用 CSS 单击时更改不同按钮的背景和字体颜色。我试过 :focus 但只适用于 Chrome
- mercurial - 如何在 tortoisehg 中变基?
- javascript - 如果找不到 ID (document.getElementById),希望 JS 继续
- angular - 从控制台触发 router.navigate
- batch-file - 如何修复批量无法正确加载网站链接?
- gatsby - 如何使用 Gatsby 制作的网站对 Strapi 中的数据进行变异?
- python - 如何创建仅在图像中显示黑色的白色蒙版?
- python - 如何查询扳手并获取元数据,尤其是列名?