user7510478
user7510478

Reputation:

how to get only subdocument from document query in mongoose

I am trying to get only subdocument out of whole document via mongoose in node.js. My database schema is as follows:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// var Items = require('./items.js');

var Items = new Schema({
    no_of_times_ordered:Number,
    item_name:String,
    item_tag:String,
    item_category:String,
    item_stock:Number,
    item_price:Number,
    item_img:String,
    item_illustrations:[String],
    item_liked:Boolean,
    no_of_likes:Number
},{ versionKey: false });


var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    foodtruck_location:String,
    foodtruck_rating:Number,
    foodtruck_tag:String,
    foodtruck_timing:String,
    foodtruck_cusine:String,
    foodtruck_img:String,
    foodtruck_logo:String,
    item_list: [Items]
},{ versionKey: false });



module.exports = mongoose.model('foodtruck',FoodTruckSchema);

The query is as given below:

var popularitems = function(req,res) {
    foodtr.find(function(err,items){
        if (err) res.send(err);
        res.json({
            status : '200',
            message:'popular items list',
            data: items
        });
    });

So I have already put query where items with foodtrucks are retrieved, but how can I only have items in response?

Upvotes: 0

Views: 700

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

You can use select or projection in your find query to get only items.

Try this:

foodtr.find({},{'item_list':1},function(err,items){ 
    if (err) res.send(err); 
    res.json({ 
        status : '200',
        message:'popular items list', 
        data: items 
    }); 
});

{} is similar to query condition, in this case it will retrieve all the documents. {'item_list':1} is to tell mongo to retrieve only item_list array(_id comes in default along with anything else).

Hope this is what you want.

Upvotes: 1

Related Questions