mongodb Mongoose:如何将架构字段设置为 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10352900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:38:08  来源:igfitidea点击:

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

mongodbmongoose

提问by Geert-Jan

Given the following schema:

鉴于以下架构:

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

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

我想email成为关键。我该如何定义?

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 _idinstead of emailbut that doesn't feel clean to me.

所以 MongoDB 会将它识别为 id 字段,并调整我的代码以引用_id而不是,email但这对我来说并不干净。

Anyone?

任何人?

回答by JohnnyHK

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

由于您使用的是 Mongoose,因此一种选择是使用电子邮件字符串作为_id字段,然后添加一个名为返回的虚拟字段以清理使用电子邮件的代码。email_id

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: trueoption in the toObject()or toJSON()call:

请注意,将 Mongoose 文档转换为纯 JS 对象或 JSON 字符串时,默认情况下不包含虚拟字段。要包含它,您必须virtuals: truetoObject()ortoJSON()调用中设置选项:

var obj = doc.toObject({ virtuals: true });
var json = doc.toJSON({ virtuals: true });