Overriding a mongoose query for a specific model

I want to automatically add a query parameter for all queries related to a particular mongoose model without affecting other models.

I saw this answer where Mongoose.Query is fixed and it will affect all mongoose models.

+3


source to share


2 answers


I see two possible simple ways to do this:

Alternative # 1

Add a static dict with the parameters you want to apply to your specific Mongoose schema:

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

      

Now when you ask, you need to do:

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

      

Alternative # 2

Implement a wrapper in a find method that always uses your specific parameters:



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

      

And use this method like this:

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

      

Multiple use

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 mean this

there will be no reuse of this problem. And now this applies to all your schematics along with your specific schema parameters:

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

      

+2


source


I was able to do this for my soft deleted items. Haven't tested it 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);

      

+1


source







All Articles