如何在Mongoose插入数据时将updatedAt设为null或禁用?
解决方案
要实现插入数据时仅保存createdAt、updatedAt设为null,更新时同时保留createdAt并更新updatedAt的需求,你需要调整Mongoose Schema的时间戳逻辑,结合预钩子(pre hook)来精确控制字段行为。以下是具体实现:
修正后的代码
const mongoose = require('mongoose'); var schema = new mongoose.Schema({ parkno:{ type:String, required:true, // 注意:原代码的`require`是拼写错误,正确为`required` unique: true }, name:{ type:String, required:true, }, contactno:{ type:String, required:true }, category:String, regno:{ type:String, required:true, unique: true }, charge:String }, { timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } }); // 处理文档保存(新建/更新)的逻辑 schema.pre('save', function(next) { if (this.isNew) { // 新文档:设置createdAt为当前时间,updatedAt设为null this.createdAt = new Date().toISOString(); // 若需要Date类型则直接用new Date() this.updatedAt = null; } else { // 更新文档:保留createdAt不变,仅更新updatedAt this.updatedAt = new Date().toISOString(); // 强制锁定createdAt,禁止修改 delete this._modified.createdAt; } next(); }); // 处理直接更新操作(如updateOne、findOneAndUpdate),这类操作不会触发save钩子 schema.pre(['updateOne', 'findOneAndUpdate'], function(next) { const update = this.getUpdate(); // 禁止修改createdAt字段 delete update.createdAt; // 设置updatedAt为当前时间 update.updatedAt = new Date().toISOString(); next(); }); const Vechdb = mongoose.model('vechdb', schema); module.exports = Vechdb;
关键说明
- 修正验证字段拼写:原代码中
require是错误写法,Mongoose字段验证的正确参数是required,不修正会导致必填字段验证失效。 - 利用Mongoose timestamps基础功能:保留
timestamps选项自动生成字段,但通过钩子覆盖默认行为。 - 分场景控制字段值:
- 新建文档(
isNew为true):给createdAt赋值当前时间,updatedAt设为null。 - 更新文档:锁定
createdAt不允许修改,仅更新updatedAt为当前时间。
- 新建文档(
- 覆盖所有更新场景:除了
save操作,updateOne、findOneAndUpdate这类直接更新操作不会触发save钩子,需要单独添加钩子处理。
如果你更倾向于完全手动定义时间字段,也可以移除timestamps选项,手动声明createdAt和updatedAt字段后用同样的钩子逻辑控制。
内容的提问来源于stack exchange,提问作者Rithik k
相关产品推荐
相关产品推荐

