Question

For an API, I am returning a list of objects from my MongoDB. To be more RESTful, I would like to add a field link to every object. My approach is to calculate it when processing the request and add the link of each object in a simple loop:

exports.list = function (req, res) {
  collection.find({}, {fields: {a: 1, b: 1, c: 1}, function (err, docs) {
    for (var i = 0; i < docs.length; i++) {
      docs[i].link = 'http://api.example.com/fooobject/' + docs[i]._id;
    }
    res.send(docs);
  });
};

However, I have the feeling that this way of doing it might not be very performant. Are there any better ways? For example, telling MongoDB directly to do such kind of calculation?

Or is it even recommended to save the full link in the database itself?

Was it helpful?

Solution

If you want to "re-shape" your documents in this way you can use the .aggregate() method instead of find:

collection.aggregate([
    { "$project": {
        "a": 1,
        "b": 1,
        "c": 1,
        "link": { "$concat": [
            "http://api.example.com/fooobject/",
            "$_id"
        ]}
     }}
],function(err,result) {

   // Output work here
})

This uses $project to "shape" your document response by selecting and creating fields. In this case there is the use of $concat in order to join the string with the value of the _id field.

To add query information to your search, see the $match operator.

For other uses, see the reference for aggregation framework operators.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top