Khaled Ramadan
Khaled Ramadan

Reputation: 832

Mongoose, How to return data related to a Schema based on specific boolean flag?

Schema called Restaurant contain isLive flag.

How to return only restaurants that are contains isLive flag to true?

I don't want to check the isLive in every query or in every aggregation, like the following:

exports.getRestaurants = async (req, res) => {
  const restaurants = await Restaurant.getAllRestaurants();
  if (!restaurants) return next();
  const liveRestaurants = restaurants.filter(restaurant => restaurant.isLive);
  res.status(200).json({ restaurants: liveRestaurants });
};

What I want to do is to filter every operation related to Restaurant schema to isLive = true

What I tried to do is using the mongoose hooks but I didn't know how to return data based on the isLive flag.

restaurantSchema.pre('aggregate', function(next) {
  console.log('pre aggregate');
  // Return data based on the isLive flag,, is it possible?
  next();
});

So, Is it possible to return values based on the isLive flag using the hooks? or any other way can solve my problem?

Upvotes: 0

Views: 161

Answers (2)

mickl
mickl

Reputation: 49975

You can create a database view in MongoDB and add your isLive as a filtering condition.

Restaurant.db.createCollection('liveRestaurants', {
    viewOn: 'restaurants',
    pipeline: [{ $match: { isLive: true } }]
});

Then you need another model using the same schema:

let Restaurant = mongoose.model('Restaurant', restaurantSchema);
let LiveRestaurant = mongoose.model('liveRestaurants', restaurantSchema, 'liveRestaurants');

and you can query your read-only model the same way you query regular one but it will ony return filtered restaurants:

let result = await LiveRestaurant.find();

Upvotes: 1

cccn
cccn

Reputation: 949

I would recommended you to use find method on your model:

exports.getRestaurants = async (req, res) => {
  const liveRestaurants = await Restaurant.find(name: 'isLive', true);
  if (!liveRestaurants) return next();
  res.status(200).json({ restaurants: liveRestaurants });
};

Upvotes: 0

Related Questions