Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to get modified json output from MongoDB + Node.js + Mongoose

How to get modified json output from MongoDB + Node.js + Mongoose

Problem

Consider my collection is store as follows in MongoDB:

  { 
    _id: 'Unique_Value',
    FieldMONGO1: 'ngfn',
    FieldMONGO2: { SomeKey: ['val1','val2','val...']  },
  }

When I retrieve using find method on Model Instance of Mongoose. I get the following JSON output:

  { 
    _id: 'Unique_Value',
    FieldMONGO1: 'NAME_value',
    FieldMONGO2: { SomeKey: ['val1','val2','val...']  },
  }

Both are exactly same.

Question: Is there any way so that I can change the field names like FieldMONGO1 to FirstName, FieldMONGO2 to NewName & _id to IdentityNo?

So that my output will be something like this:

  { 
    IdentityNo: 'Unique_Value',
    FirstName: 'ngfn',
    NewName: { SomeKey: []  },
  }

Know Solution: Is to get the JSON output as is and then change field (attribute) name in Node.js code. But here the problem is, it becomes a blocking code. Which can create overhead on server if huge data is requested.

Could anyone help me out in find out some efficient way of doing the same?

Advance Thanks

Problem courtesy of: Amol M Kulkarni

Solution

check out Virtuals in mongoose.

check out the example in the reference link.

if you tweak like

urSchema.virtual('FirstName').get(function () {
  return this.FieldMONGO1;
});

you can do it.

check this answer on SO.

Solution courtesy of: mithunsatheesh

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to get modified json output from MongoDB + Node.js + Mongoose

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×