Sending JSON with 'id' instead of '_id'

5,403 views
Skip to first unread message

Charlie

unread,
Jul 13, 2011, 10:07:06 PM7/13/11
to Mongoose Node.JS ORM
Any suggestions on what would be the cleanest and simplest way of
always sending JSON document strings with the '_id' attribute renamed
to 'id'?

I'm building an API and I want the client to always see 'id for every
document, as some client-side software (Backbone) depends on it.

Thanks

addisonj

unread,
Jul 14, 2011, 4:51:12 PM7/14/11
to Mongoose Node.JS ORM
A virtual property on all your models is a pretty safe and easy way to
do it.

An example:

Schema.virtual('id')
.get(function() {
return this._id.toHexString();
});

Aaron Heckmann

unread,
Jul 15, 2011, 6:58:52 AM7/15/11
to mongoo...@googlegroups.com
ThingSchema.methods.toBackbone = function () {
  var obj = this.toObject();
  obj.id = obj._id;
  delete obj._id;
  return obj;
}

Always send the output of the method above.
--
Aaron


Kirk Bushell

unread,
Jul 20, 2013, 7:01:44 PM7/20/13
to mongoo...@googlegroups.com
How do you do this across a collection though without having to loop through them every time? I've tried every possible combination of using virtuals/getters in combation with setting toJson/toObject settings on the schema, all to no avail. _id is ALWAYS returned, and it foobar's the JSON output.

Jason Crawford

unread,
Jul 20, 2013, 7:07:18 PM7/20/13
to mongoo...@googlegroups.com
Hmm, Backbone has a simpler way: When you define your model, just set the idAttribute property to '_id'. The Backbone docs explicitly suggest this if you're using Mongo: http://backbonejs.org/#Model-idAttribute

I'm doing this in a Mongoose + Backbone app and it's working fine. In fact, I defined my own Model class like this:

    var Model = Backbone.Model.extend({
      idAttribute: '_id',
      ...
    }

And then all my models extend that Model instead of extending Backbone.Model directly. Works great.

-Jason

--
Blog: http://blog.jasoncrawford.org  |  Twitter: @jasoncrawford



--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages