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
Mongoose: how to set a schema-field to be the ID?
提问by Geert-Jan
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?
我想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 _id
instead of email
but 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 _id
field and then add a virtual fieldnamed email
that returns the _id
to 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: true
option in the toObject()
or toJSON()
call:
请注意,将 Mongoose 文档转换为纯 JS 对象或 JSON 字符串时,默认情况下不包含虚拟字段。要包含它,您必须virtuals: true
在toObject()
ortoJSON()
调用中设置选项:
var obj = doc.toObject({ virtuals: true });
var json = doc.toJSON({ virtuals: true });