I have a book model. Here’s its schema
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();
});
When a goods of a book is created, I have to update the book’s lowest price if the goods’ price is lower than the origin one. For I need to know the origin lowest price, I can’t use Book.update(), which skips the pre-save hook, but use Book.findById(id).select('lowestPrice') to find the book than update it. The problem was that I didn’t want to select the title field, thus when it came to the pre-save hook, a TypeError occured for this.title was undefined. Are there ways to skip the pre-save hook?
Use
Book.updatewith a condition that will only select the document if the new price is lower than the original: