2

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

3
  • stackoverflow.com/questions/7093441/… Commented Feb 7, 2013 at 13:12
  • Why are you using generic field names like FieldMONGO1 in your docs? Commented Feb 7, 2013 at 13:13
  • 2
    @JohnnyHK Just for the sake of better understanding... Commented Feb 7, 2013 at 13:15

1 Answer 1

5

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.

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

1 Comment

If have some solution without mongoose as well, let me know.. Thanks for nice answer

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.