Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: how to set a schema-field to be the ID?

Given the following schema:

var UserSchema = new Schema({    , email   :  { type: String }    , passwordHash   :  { type: String }    , roles  :  { type: [String] } }); 

I'd like email to be the key. How can I define this?

I could do:

var UserSchema = new Schema({        , _id:  { type: String }        , passwordHash   :  { type: String }        , roles  :  { type: [String] }     }); 

so MongoDB would recognize it as the id-field, and adapt my code to refer to _id instead of email but that doesn't feel clean to me.

Anyone?

like image 463
Geert-Jan Avatar asked Apr 27 '12 14:04

Geert-Jan


People also ask

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.

What is the type of ID in Mongoose?

By default, MongoDB creates an _id property on every document that's of type ObjectId. Many other databases use a numeric id property by default, but in MongoDB and Mongoose, ids are objects by default.

What is object ID in Mongoose?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running.

What is __ V in MongoDB?

Posted On: Jun 24, 2021. In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.


1 Answers

Since you're using Mongoose, one option is to use the email string as the _id field and then add a virtual field named email that returns the _id to clean up the code that uses the email.

var userSchema = new Schema({     _id: {type: String},     passwordHash: {type: String},     roles: {type: [String]} });  userSchema.virtual('email').get(function() {     return this._id; });  var User = mongoose.model('User', userSchema);  User.findOne(function(err, doc) {     console.log(doc.email); }); 

Note that a virtual field is not included by default when converting a Mongoose doc to a plain JS object or JSON string. To include it you have to set the virtuals: true option in the toObject() or toJSON() call:

var obj = doc.toObject({ virtuals: true }); var json = doc.toJSON({ virtuals: true }); 
like image 184
JohnnyHK Avatar answered Sep 21 '22 04:09

JohnnyHK