0

I am struggling to override the attribute name in one of my models.

I would like to return an object to the front end (via JSON) with a field called id.

Now the problem comes that there is a field called _id (generated by mongo), that I cannot seem to get rid of.

I can override the id fine but is still returned as _id.

[Object]
0: Object
$$hashKey: "007"
_id: 123

I would like it to be [Object] 0: Object $$hashKey: "007" id: 123

I have tried many hash manipulations, reject, except, and looping over and constructing, but cannot simply rename the field, or remove it for that matter.

Thanks

1
  • 2
    you cannot. The _id field is mandatory in all MongoDB documents (user generated documents, anyway) Jan 16, 2014 at 22:45

2 Answers 2

0

The "_id" field is mandatory in MongoDB documents. The manual says:

If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

So you won't be able to work your way around this one.

0

Easiest way was to override the as_json method and remove the hash there.

def as_json(*args)
   super.tap { |hash| hash["id"] = hash.delete "_id" }
end

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.