Wednesday, 7 June 2017

How to get particular documents of a schema which does not have empty array of referenced schema

My code is as shown below:

foodtruck.js

var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });

items.js

var ItemSchema = new Schema({
    item_name: String,
    item_description: String,
    item_illustrations: [String],
    item_stock: {
        type: Number,
        default: 0
    } ,
    no_of_likes: {
        type: Number,
        default: 0
    }
}, {
    versionKey: false
});

My query is as shown below:

const searchItems = (req, res) => {
    let item_name = req.query.item_name;
    foodtr.find().populate({
        path: 'item_list',
        match: {
            item_name: item_name,
            item_stock: { $ne: 2 }
        }
    }).exec(function(err, foodtrucks) {
        res.json({
            status: '200',
            message: 'searched items',
            data: foodtrucks
        });
    });
};

What I want here is, I want only those foodtrucks in which queried item_name matches with referenced item_name , otherwise , I do not want to show that particular foodtruck. Right now, I am getting also those foodtruck in which item_list is empty array. How to alleviate this situation?



via M thaker

No comments:

Post a Comment