V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lry1994
V2EX  ›  Node.js

mongoose pre 中间件使用疑问

  •  1
     
  •   lry1994 · 2018-10-16 10:04:03 +08:00 · 2337 次点击
    这是一个创建于 1991 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2769 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 12:49 · PVG 20:49 · LAX 05:49 · JFK 08:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.