igreka
igreka

Reputation: 350

MongooseJS: Hide Specific Documents From Query

I have a User schema with a activated field of Boolean type. I want queries to only return documents which have activated: true. And I hope there is a more efficient and DRY way of doing so than adding a conditional to every find, findOne, or findById.

What would be the most effective approach?

Upvotes: 0

Views: 442

Answers (2)

Derick Bailey
Derick Bailey

Reputation: 72868

while there may be some way to do this, it is generally a bad idea to always hide this information.

speaking from experience trying to do this with other languages and database systems, you will, at some point, want / need to load items that are not actived. but if you always and only return activated items, you'll never be able to get the list you need.

for your purposes, i would recommend creating a findActive method on your schema:


someSchema.static("findActive", function(query, cb){
  // check if there is a query and callback
  if (!cb){
    cb = query;
    query = {};
  }

  // set up an empty query, if there isn't one provided
  if (!query) { query = {}; }

  // make sure you only load activated items
  query.activated = true;

  // run the query
  this.find(query, cb);
});

with this method, you will have a findActive method the same as findOne, but it will always filter for activated items.

MyModel.findActive(function(err, modelList){ ... });

and it optionally supports additional query filters

MyModel.findActive({some: "stuff"}, function(err, modelList){ ... });

Upvotes: 1

oleh.meleshko
oleh.meleshko

Reputation: 4795

You might want to look at Mongoose Query middleware here

Query middleware is supported for the following Model and Query functions.

  • count
  • find
  • findOne
  • ...

For example:

User.pre('find', function() {
  console.log(this instanceof mongoose.Query); // true
  this.activated = true;
});

Upvotes: 1

Related Questions