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?
On my journey to explore MongoDB and Mongoose's powerful features over the years, I encountered something called pre and post hooks, few years back. They are simple yet powerful tools with which you can manipulate model instances, queries, perform validation before or after an intended database operation etc.
According to the official mongoose documentation here – Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.
Pre- and post-execution hooks are Processing scripts that run before and after actual data processing is performed. This can be used to automate tasks that should be performed whenever an algorithm is executed.
Mongoose middleware are functions that can intercept the process of the init , validate , save , and remove instance methods. Middleware are executed at the instance level and have two types: pre middleware and post middleware.
Use Book.update
with a condition that will only select the document if the new price is lower than the original:
Book.update({_id: id, lowestPrice: {$gt: price}}, {$set: {lowestPrice: price}},
function (err, numberAffected) {
if (numberAffected > 0) {
// lowestPrice was updated.
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With