Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose (mongodb) Alias _id field

Tags:

Is it possible with mongoose use a different name, in my case uppercase 'ID', as an alias for the schema _id field? Would I need to add a virtual or is there another way of setting this up?

Any help gratefully received thanks.

like image 733
Chin Avatar asked Apr 28 '12 12:04

Chin


People also ask

What is _ID in mongoose?

From the documentation: Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.

What is alias in mongoose?

The easiest way is to specify alias in the schema: let s = new Schema({ _id: { type: String, alias: "ID" } }); This automatically creates both getter and setter, so it is possible to use ID everywhere instead of _id . Mongoose documentation on aliases.

What is __ V 0 in mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.

What is Save () in mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.


2 Answers

You would use a virtual attribute for that. As in:

yourSchema.virtual('ID').get(function() { return this._id; }); 
like image 121
JohnnyHK Avatar answered Sep 20 '22 14:09

JohnnyHK


The easiest way is to specify alias in the schema:

let s = new Schema({     _id: { type: String, alias: "ID" } }); 

This automatically creates both getter and setter, so it is possible to use ID everywhere instead of _id.

Mongoose documentation on aliases

like image 24
R. V. Avatar answered Sep 21 '22 14:09

R. V.