Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip mongoose pre-save hook?

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?

like image 833
Trantor Liu Avatar asked Aug 12 '12 03:08

Trantor Liu


People also ask

What is pre hook in mongoose?

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.

What is the use in pre In mongoose?

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.

What are pre and post hooks?

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.

What is middleware in mongoose?

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.


1 Answers

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.
        }
    }
);
like image 118
JohnnyHK Avatar answered Oct 15 '22 18:10

JohnnyHK