node.js - Mongoose:如何在保存前手动设置_id?

标签 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?

为什么 this.name 未定义

最佳答案

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

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

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

关于node.js - Mongoose:如何在保存前手动设置_id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55523593/

相关文章:

node.js - 如何在 Express 中访问 mongoose 虚拟对象

javascript - 从 json 字符串中提取某些列和行

node.js - NodeJS : Error: read ECONNRESET at TCP. onStreamRead (内部/stream_base_commons.js:111:27)

node.js - mongoose 不会获取更新的数据,除非重新启动nodejs

javascript - 如何修复 "trim"在 Mongoose 模式中不起作用

node.js - 像 mongoose 一样简单的连接 SQL

Mongoose DB 观察特定属性变化

Node.js 与 MS Exchange EWS 集成

node.js - socket.io-client 建立连接时如何设置请求 header

javascript - 尝试将表单元素保存到 mongoDB 时无法读取未定义错误的属性