MongoDB: output 'id' instead of '_id'

Issue

I am using mongoose (node), what is the best way to output id instead of _id?

Solution

I create a toClient() method on my models where I do this. It’s also a good place to rename/remove other attributes you don’t want to send to the client:

Schema.method('toClient', function() {
    var obj = this.toObject();

    //Rename fields
    obj.id = obj._id;
    delete obj._id;

    return obj;
});

Answered By – evilcelery

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.