Code Snippet - Return Json Response for Express.js

2014/7/51 min read
bookmark this
Responsive image
A Sample Code Snippet for create api return json object
   var tagQ = yourCollection.find({}).limit(20);
    yourCollection.exec(function (err, resultCollections) {
        var array = [];
        var result = {};
        resultCollections.forEach(function (tag) {
            array.push(tag.TagId);
        });
        result.name = 'name';
        result.id = 'id';
        result.items = array;
        res.json(result);
    });

above all will return json object like following.


{
    "name": "name",
    "id": "id",
    "items": [
        "your item1",
        "your item2"
    ]
}