Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js: is it possible to change name of ObjectId?

Some question about mongo ObjectId in mongoose

1) Can be ObjectId field by named not as _id? And How to do that? When I do in my code:

MySchema = new mongoose.Schema({
    id  : mongoose.Schema.ObjectId
});

it changes nothing.

2) If I have objectId field called _id is it possible to return from request another name for this field (for example just "id" - to send it on the in web response);

3) And question just for understanding: why is the ObjectId _id field accessible through "id" property not "_id"?

Thanks, Alex

like image 468
WHITECOLOR Avatar asked Oct 07 '22 08:10

WHITECOLOR


1 Answers

The "_id" element is part of the mongodb architecture which guarantee that every document in a collection can be uniquely identified. This is especially important if you use sharding to allow unique identifier across disparate machine. Therefore this is a design choice so there is no way to get ride of it :)

The default value for _id are generated as follows:

  • timestamp
  • hash of the machine hostname
  • pid of the generating process
  • increment

but you can use whatever value you want as long is unique.

If it's easier for you think about the _id of something which has to be there, but you really don't care about :) Just leave the system to auto generate it and use your own identifier.

So if you still wanna create your own "id" execute something like that:

db.mySchema.ensureIndex({"id": 1}, {"unique" : true})

but make sure that is really unique and it doesn't conflict with the API you use.

2) Rename it on the application side, just before sending it as the web response.

3) I think this is because of the API you use. Maybe the author found it more logical to return the id instead of _id ? Honestly never tried mongoose :)

like image 177
golja Avatar answered Oct 13 '22 11:10

golja