Search code examples
mongoosemongoose-schemamongoose-populate

How to have selective field for deep population query in mongoose


My query is as shown below:

orderSubInfo.find({
    'order_id': {
        $in: orderArray
    }
}).populate({
    path: 'order_id',
    populate: {
        path: 'foodtruck_id',
        model: 'foodtruck'
    }
}).exec().then((info) => {
    res.json({
        status: '200',
        message: 'Your OTP',
        data: info
    })
}).catch((err) => {
    res.json({
        status: '500',
        message: 'Oops,something went wromg'
    })
});

Now what here happens is after populate {path:foodtruck_id,model:'foodtruck}. I get unnecessary fields. But I want to have foodtruck_name,foodtruck_location only. So how should i modify my query?


Solution

  • Select only the fields you want to include (mongoose population):

    populate: {
        path: 'foodtruck_id',
        model: 'foodtruck',
        select: 'foodtruck_name foodtruck_location' //to exclude _id add -_id
    }