猫鼬:如何将架构字段设置为ID? [英] Mongoose: how to set a schema-field to be the ID?

查看:107
本文介绍了猫鼬:如何将架构字段设置为ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下架构:

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

我希望email是关键. 我该如何定义呢?

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

我可以做到:

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

,因此MongoDB会将其识别为id字段,并修改我的代码以引用_id而不是email,但这对我来说并不干净.

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.

有人吗?

推荐答案

由于您使用的是Mongoose,一种选择是将电子邮件字符串用作_id字段,然后添加

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);
});

请注意,将Mongoose文档转换为纯JS对象或JSON字符串时,默认情况下不包含虚拟字段.要包含它,您必须在 toObject()

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 });

这篇关于猫鼬:如何将架构字段设置为ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆