2

I'm using nodejs to query mongodb and want to output json with customized field names.

For example, original json from MongoDB maybe

    {id:1, text:"abc"}

I'd like to output it as

    {ObjectID:1, DisplayText:"abc"};

I understand MongoDB has the $project operator in its aggregate framework but not sure how to use them in NodeJS.

The mongodb nodejs packages I'm using are

    var mongo = require('mongodb');
    var monk = require('monk');
    var db = monk('server:port/mydb');

Appreciate any advice on this.

2
  • Maybe this will get you started: stackoverflow.com/questions/16252208/… Commented May 30, 2014 at 9:28
  • Thanks, John. Would you know which mongodb package to use? I used similar implementation and get TypeError: Object #<Manager> has no method 'collection'. Commented May 30, 2014 at 9:47

2 Answers 2

9

If you are using monk as you appear to be then you can access the underlying node native driver collection type via the .col accessor on your selected collection object:

  var db = require('monk')('localhost/test')
    , collection = db.get('example');

  collection.col.aggregate(
    [
      { "$project": {
        "_id": 0,
        "ObjectID": "$_id",
        "DisplayText": "$text"
      }}
    ],
    function(err,result) {

      console.log( JSON.stringify( result, undefined, 4 ) );

    }
  );

Note that methods such as .aggregate() retrieved in this way are not wrapped in the promise object as the standard monk collection objects are. But at least this shows you how to access and use $project to re-shape your document.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, Neil. This seems working though I get a different error: "aggregation result exceeds maximum document size (16MB)", but I believe this should be a separate issue I should work on.
@user3492125 As it stands this is trying to output the whole collection to what is essentially an array, so you probably do not want the whole collection if you are sending a response to the client. There are other approaches but probably most specific to you right now is the $match pipeline operator in order to reduce the results. At least you know how to use aggregate with monk now. Feel free to post other questions to stack overflow if you have them.
Neil, you got a sharp mind. That's exactly what I missed out earlier. Thank you.
0

Have a look at Virtuals in Mongoose http://mongoosejs.com/docs/guide.html#virtuals

You could do something like:

someSchema.virtual('text').get(function() {
    return this.DisplayText;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.