Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add conditions on mongoose pre-find middleware

I'm using mongoose-delete plugin.

I want to build a simple mongoose middleware so I add {deleted:false}to every find query on that schema.

var mongoose = require('mongoose'),
    mongooseDelete = require('mongoose-delete'),
    Schema = mongoose.Schema;

var MySchema = new Schema({
  name: {type: String, required: true}
});

MySchema.plugin(mongooseDelete, {deletedAt: true, deletedBy: true});

MySchema.pre('find', function (next){
  // I want to add {deleted: false} to the queries conditions
});

How should I implement the pre-find middleware?

like image 882
Facundo Chambo Avatar asked Oct 03 '15 21:10

Facundo Chambo


1 Answers

In pre-find middleware, this is the Query object so you can add {deleted: false} to the query using:

MySchema.pre('find', function() {
    this.where({deleted: false});
});
like image 128
JohnnyHK Avatar answered Sep 24 '22 19:09

JohnnyHK