Nodejs mongoose pre 中间件使用疑问
Nodejs mongoose pre 中间件使用疑问
1 出现 Cannot set property ‘updateAt’ of undefined 错误,但是数据库里是有数据的
"use strict"
const PostSchema = Schema({
title: String,
meta:{
createdAt:{
type:Date,
default:Date.now()
},updateAt:{
type:Date,
default:Date.now()
}
}
}
);
PostSchema.pre('save',function(next){
if(this.isNew){//Document.prototype.isNew mongoose 自己会识别
this.meta.createdAt = this.meta.updateAt=Date.now()
}else{
console.log('notnew')
this.meta.updateAt = Date.now();
}
console.log('save')
next();
})
PostSchema.pre('findOneAndUpdate',function(next){
this.meta.updateAt = Date.now(); // Cannot set property 'updateAt' of undefined
console.log('findOneAndUpdate')
next();
})
}
module.exports = mongoose.model('Post', PostSchema);
2、然后改成
PostSchema.pre(/^find/,function(next){
console.log('find')
this.meta.updateAt = Date.now();
next();
})
没有报错,但是没有输出‘ find',明显没执行
3.update 的时候用来 save 方法出现这个错误 :MongoError: E11000 duplicate key error collection: koa_vue_blog.posts index: id dup key: { : ObjectId('5bc1fa4354266f0d1d5e91c1') }
let o =new Post({
_id:id,
...ctx.request.body
})
let result= await dbHelper.Save(o);
不是 this.isNew 会自己判断出来吗?
在Node.js中,Mongoose是一个功能强大的对象数据建模(ODM)库,用于MongoDB和Node.js应用。Mongoose提供了各种中间件,包括文档生命周期中间件(如pre
和post
)。pre
中间件允许你在Mongoose文档的特定生命周期事件之前执行代码。
下面是一个使用pre
中间件的示例,演示如何在保存文档之前执行一些操作:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// 定义一个简单的Schema
const userSchema = new Schema({
name: String,
email: String
});
// 使用pre中间件在保存之前添加时间戳
userSchema.pre('save', function(next) {
if (!this.createdAt) {
this.createdAt = new Date();
}
next();
});
// 创建Model
const User = mongoose.model('User', userSchema);
// 创建一个新用户并保存
const newUser = new User({ name: 'John Doe', email: 'john@example.com' });
newUser.save((err, user) => {
if (err) return console.error(err);
console.log('User saved:', user);
});
在这个例子中,我们在userSchema
上定义了一个pre('save')
中间件,该中间件在每次保存文档之前都会检查是否设置了createdAt
字段,如果没有,则设置当前时间。这样,每个保存的文档都会有一个创建时间戳。
通过这种方式,你可以轻松地在保存文档之前执行自定义逻辑,例如验证、格式化数据或添加额外的字段。