1 there is a Cannot set property "updateAt" of undefined error, but there is data in the database
"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, and then change it to
PostSchema.pre(/^find/,function(next){
console.log("find")
this.meta.updateAt = Date.now();
next();
})
No error is reported, but no output "find", is obviously not executed
This error occurs in the save method when 3.update
: 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);
won"t this.isNew judge it for himself?