mongoose pre 中间件使用疑问

2018-10-16 10:04:03 +08:00
 lry1994

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

2363 次点击
所在节点    Node.js
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/498002

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX