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?
Since you’re using Mongoose, one option is to use the email string as the
_idfield and then add a virtual field namedemailthat returns the_idto clean up the code that uses the 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: trueoption in thetoObject()ortoJSON()call: