mojo mojo - 25 days ago 8
JSON Question

How can i send only particular field in json response using node and express.js?

[
{
id: 6dcba0f57c9b73cc1,
USER_ID: '945',
ORDER_ID: '35220',
PRODUCT_ID: '9982',
CODE: '418567066',
POINTS: '2000'

},
{
id: 4dcba0f57c9b73cc7,
USER_ID: '945',
ORDER_ID: '43521',
PRODUCT_ID: '1071',
CODE: '4004091261',
POINTS: '1000',
},
{ id: dcba0f57c9b73cce,
USER_ID: '945',
ORDER_ID: '13594',
PRODUCT_ID: '2482',
CODE: '7592231244',
POINTS: '2000',
},
{
id: 0f57c9b73cc74dcba,
USER_ID: '345',
ORDER_ID: '43528',
PRODUCT_ID: '1071',
CODE: '4004091267',
POINTS: '1000',
}
]


Above documents stored in my pointsummaries collection .

id
USER_ID
ORDER_ID
PRODUCT_ID
CODE
POINTS


instead of sending all the above fields in every document . i need to send only

USER_ID
ORDER_ID
CODE


Below is my controller code which will display/send only
USER_ID: '945'
point details.

exports.userpos = function(req, res) {
console.log(req.params.id)
PointSummary.find({'USER_ID':'945'}).exec(function (err, PointSummarys) {
if(err) { return handleError(res, err); }
//return res.status(200).json(PointSummarys);
return res.status(200).json({});
});
};


how can i solve this ?

Answer

You can pass all the fields that you want to be returned in the db query.

exports.userpos = function(req, res) {
    console.log(req.params.id)
    PointSummary.find({'USER_ID':'945'}, {
        'USER_ID': 1,
        'ORDER_ID': 1,
        'CODE': 1
    }).exec(function (err, PointSummarys) {
    if(err) { return handleError(res, err); }
     //return res.status(200).json(PointSummarys);
     return res.status(200).json({});
  });
};

Side note: Ideally, you would want to keep your key names in lower case. user_id instead of USER_ID