【问题标题】:How to Ensure a Unique Email, userName will Enter into MongoDB using Mongoose如何确保唯一的电子邮件,用户名将使用 Mongoose 进入 MongoDB
【发布时间】:2015-02-22 05:51:10
【问题描述】:
db.UserSchema = new db.Schema({   
    userName: {type:String,
        unique:true,
        required:true,index:true},
    emailId: {type:String,
        unique:true,
        required:true,index:true},
    password: {type:String,
        required:true},
    contactNumber: String,
    region: String,
    isActive:Boolean,
    lastLoginDateTime:Date
});

上面是我想放入 MongoDB 的架构,但电子邮件和用户名应该是唯一的,我无法做到这一点。

【问题讨论】:

  • 尝试 username:{type:String, required:true, unique:true} 并对电子邮件执行相同操作
  • 上述问题需要一点温柔的爱和关怀来满足关于格式的 SO 标准(我已经做了一点点 - 如果它被接受)并使问题更容易被接受那些希望对您有所帮助的人 稍微扩展您的问题,使其更清晰,并且 - 如果可以的话 - 提供一些解决方案尝试或一些指向您正在阅读的文档的链接。这是问题的链接:stackoverflow.com/help/how-to-ask
  • @joao 它不能那样工作,我试过了。
  • 您是否删除了 index:true 部分?指定 unique:true 已经创建了索引。
  • @joao 是的,亲爱的,我也删除了它,但仍然无法正常工作:(

标签: javascript node.js mongodb mongoose


【解决方案1】:

我试过这个方法,效果很好

db.UserSchema = new db.Schema({ userName: {type: String, index: {unique: true, dropDups: true}}, emailId: {type: String, index: {unique: true, dropDups: true}}, password: {type:String, required:true}, contactNumber: String, region: String, isActive:Boolean, lastLoginDateTime:Date });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多