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.
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.
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.
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.
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.
You would use a virtual attribute for that. As in:
yourSchema.virtual('ID').get(function() { return this._id; });
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With