
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 会自己判断出来吗?