Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .where() with after a populate in mongoose

So i have two schemas

var subcategories = new Schema({
    //the category being populated needs to be the same case ;
    categoryId: [{ type: Schema.ObjectId, ref: 'categories' }],
    name: String,
    description:  String,
    display:  Boolean,
    active: Boolean,
    sortOrder:  Number,
    createDate: Date,
    updateDate: Date,
    type:  String,
    startDate: Date,
    endDate: Date,
    authorId: String
});

And

var categories = new Schema({
    name: String,
    description:  String,
    display:  Boolean,
    active: Boolean,
    sortOrder:  Number,
    createDate: Number,
    updateDate: Number,
    type:  String,
    startDate: Date,
    endDate: Date,
    authorId: String
});

And I want to have a query to only return if active/display is true in both category/subcategory. What I'm having trouble with is how to properly set the filter for categoryId after a populate. Here is what I have so far

exports.generateList = function (req, res) {
    subcategories
            .find({})//grabs all subcategoris
            .where('categoryId').ne([])//filter out the ones that don't have a category
            .populate('categoryId')
            .where('active').equals(true)
            .where('display').equals(true)
            .where('categoryId.active').equals(true)
            .where('display').in('categoryId').equals(true)
            .exec(function (err, data) {
            if (err) {
                console.log(err);
                console.log('error returned');
                res.send(500, { error: 'Failed insert' });
            }

            if (!data) {
                res.send(403, { error: 'Authentication Failed' });
            }

            res.send(200, data);
            console.log('success generate List');
        });
    };

The only problem is even when i have a category with display = false it will still get returned.

like image 356
Austin Davis Avatar asked Feb 24 '14 18:02

Austin Davis


1 Answers

To build query conditions for populated references there are special ways that can be referenced here:

Query conditions and other options

What if we wanted to populate our fans array based on their age, select just their names, and return at most, any 5 of them?

Story
  .find(...)
  .populate({
    path: 'fans',
    match: { age: { $gte: 21 }},
    select: 'name -_id',
    options: { limit: 5 }
})
.exec()

So in your case, you need to do something similar to this:

subcategories
  .find({})//grabs all subcategoris
  .where('categoryId').ne([])//filter out the ones that don't have a category
  .where('active').equals(true)
  .where('display').equals(true)
  .populate({
    path: 'categoryId',
    match: {
      active: true,
      display: true,
    }
  })
  .exec()
like image 188
srquinn Avatar answered Sep 19 '22 06:09

srquinn