4

I want to automatically add a query option for all queries related for a specific mongoose model without affecting other models

I saw this answer where Mongoose.Query is patched and that will affect all mongoose models.

2 Answers 2

6

I was able to do this for my soft deleted items. Haven't tested it extensively yet though.

function findNotDeletedMiddleware(next) {
    this.where('deleted').equals(false);
    next();
}

MySchema.pre('find', findNotDeletedMiddleware);
MySchema.pre('findOne', findNotDeletedMiddleware);
MySchema.pre('findOneAndUpdate', findNotDeletedMiddleware);
MySchema.pre('count', findNotDeletedMiddleware);
Sign up to request clarification or add additional context in comments.

Comments

5

I see two possible easy ways to do this:

Alternative #1

Add a static dict with the options you want to be applied to your specific Mongoose schema:

FooSchema.statics.options = {
    ...
};

Now, when you query you need to do:

Foo.find({}, null, Foo.options, function(err, foos) {
    ...
});

Alternative #2

Implement a wrapper to the find method that always uses your specific options:

FooSchema.statics.findWithOptions = function(query, next) {
    var options = { ... };
    this.find(query, null, options, next);
};

And use this method like so:

Foo.findWithOptions({}, function(err, foos) {
    ...
})

Reusability

To make these wrapper methods more reusable, you can make a dict with all your wrappers:

var withOptionsWrappers = {
    findWithOptions: function(query, next) {
        this.find(query, null, this.options, next);
    },
    findByIdWithOptions: ...
    findOneWithOptions: ...
    ...
};

Since we're referring to this there will be no problem reusing this. And now have this be applied to all your schemas along with your schema specific options:

FooSchema.statics = withOptionsWrappers;
FooSchema.statics.options = {
    ...
};
BarSchema.statics = withOptionsWrappers;
BarSchema.statics.options = {
    ...
};

2 Comments

Thank you for the answer but actually i want to add this option to all queries (find,findById,update,remove...) so i need to create wrapper for each query for each model !
@eyadof added a section in my answer that gives a suggestion how you can reuse it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.