【问题标题】:how to make a variable a unique key in mongoose?如何使变量成为猫鼬中的唯一键?
【发布时间】:2014-05-01 09:47:38
【问题描述】:

例如,如果我有这个架构

var userSchema = mongoose.Schema({
    username: String,
    email: String,
    password: String,
    _todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});

我希望用户名是其他用户无法复制的唯一键。我该怎么做?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您可以使用unique 属性添加约束。这还将为您的集合中的字段添加一个“唯一”索引:

    var userSchema = mongoose.Schema({
        username: { type: String, unique: true },
        email: String,
        password: String,
        _todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
    });
    

    【讨论】:

    • 正确答案如下,特别是考虑到“您应该使用 MongoDB shell 创建索引,而不是依赖 mongoose 为您完成。”
    【解决方案2】:

    我遇到了同样的问题。但不能通过接受的答案来解决。

    对于我的示例非常简单,只需将name 设为唯一即可。

    var FoolSchema = Schema({
        name: {
          type: String,
          unique: true,
          index: true,
          required: true
        }
    })
    

    我可以每次都保存重复的名称。

    然后我找到了这个链接: https://mongoosejs.com/docs/faq.html#unique-doesnt-work

    解决方案是来自mongoDBcreateIndex,而不是来自猫鼬。

    1. 启动mongo shell mongouse yourdbName
    2. 运行db.foos.getIndexes()(看不到"unique" : true,
    3. db.foos.createIndex( { "name": 1 }, { unique: true } )
    4. 尝试第 2 步。结果应包含unique

    希望它可以帮助某人。

    编辑 如果您的 foo 表集合包含重复的名称,您可能会在第 3 步中遇到错误:

    {
        "ok" : 0,
        "errmsg" : "E11000 duplicate key error collection: mategoal-dev.categories index: name_1 dup key: { : \"TheName\" }",
        "code" : 11000,
        "codeName" : "DuplicateKey"
    }
    

    然后先删除所有数据或重复数据(未测试):

    db.foos.remove({})
    

    然后再次尝试第 3 步。

    【讨论】:

    • Restart mongo 在不使用 mongo shell 解决方案的情况下使其工作。至少它对我有用。
    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2015-02-24
    • 2014-04-01
    • 2021-02-11
    • 2022-11-10
    • 2016-11-25
    相关资源
    最近更新 更多