如何跳过猫鼬预保存钩子?

Tra*_*Liu 5 hook middleware save pre mongoose

我有一个书本模型。这是它的架构

BookSchema = new Schema({
    title: String
    , lowestPrice: Number
});
BookSchema.path('title').required(true);
Bookchema.pre('save', function (next) {
    try {
        // chai.js
        expect(this.title).to.have.length.within(1, 50);
    } catch (e) {
        next(e);
    }
    next();
});
Run Code Online (Sandbox Code Playgroud)

创建一本书的商品时,如果商品的价格低于原始价格,我必须更新该书的最低价格。因为我需要知道来源最低价格,所以我不能使用Book.update(),它跳过了预保存钩子,而是Book.findById(id).select('lowestPrice')用来查找书而不是更新它。问题是我不想选择该title字段,因此当涉及到预保存挂钩时,TypeError发生的 forthis.title是未定义的。有没有办法跳过预保存钩子?

Joh*_*yHK 3

Book.update与仅在新价格低于原始价格时才选择文档的条件一起使用:

Book.update({_id: id, lowestPrice: {$gt: price}}, {$set: {lowestPrice: price}},
    function (err, numberAffected) {
        if (numberAffected > 0) {
            // lowestPrice was updated.
        }
    }
);
Run Code Online (Sandbox Code Playgroud)