【问题标题】:Mongoose schema option change doesn't reflect in databaseMongoose 模式选项更改未反映在数据库中
【发布时间】:2020-04-23 06:32:21
【问题描述】:

我有一个如下定义的猫鼬模式:

{
    Username: {
        type: String,
        unique: true,
        required: true,
    },
    Password: {
        type: String,
        required: true,
        minlength: 10,
        maxlength: 20
    }
}

例如,在我们启动正在运行的应用程序的生产版本后,如果我想将“用户名”的“唯一”更改为 unique: false,我应该怎么做?

所以在我的机器上,当服务器运行时,我使用用户名和密码创建了一个用户,mongo 为我创建了用户,现在我在代码中手动将唯一选项值更改为 unique: false 并重新启动我的服务器,mongo 抛出一个错误提示 "E11000 duplicate key error collection: TFM-Dev-Server.admins index: Username_1 dup key: { Username: \"admin\" }"。但我确实将 Unique 选项更改为 false。只有当我删除我的数据库时它才有效。但是我不能继续使用用户数据来删除我的生产数据库,因为这样的小改动。有人请告诉我如何实施最好的方法。

在我的应用程序中,架构在我的应用程序的几个区域经常更改,我想在不停止和删除生产服务器的数据库的情况下处理它们。

谢谢

【问题讨论】:

  • 不能删除 db 而不是删除 index 吗? db.collection.dropIndexes()
  • 只需删除 Username 的唯一索引(通过在猫鼬模式中定义创建):db.collection.dropIndex("Username_1");db.runCommand( { dropIndexes: "collection", index: "Username_1" });

标签: node.js mongodb express mongoose mongoose-schema


【解决方案1】:

为什么会出现错误:
第一次使用unique: true 创建模式时,猫鼬会自动为该字段创建一个唯一索引(即Username)。当您将其从代码中更改为 unique: false 时,更改不会撤消 mongoose 所做的事情,唯一索引仍将在数据库中。因此,每当您尝试插入另一个用户名已存在的文档时(即使将唯一选项切换为false),您都会收到索引重复键错误。

解决办法:
首先,您应该知道unique 选项不是验证或强制Username 字段唯一的方法,而是构建MongoDB 唯一索引的帮助器。 Source.
如果您使用unique 选项进行验证,那么正确的做法是删除它并实施其他逻辑以确保Username 字段的唯一性。但是,如果您有意使用unique 选项来自动创建索引,那么您需要在将unique 选项切换为false 时删除唯一索引。你可以在 mongo shell 中这样做:

db.Admin.dropIndex( { "Username" : -1 } )

【讨论】:

    【解决方案2】:

    这是因为mongoose 在您首次定义唯一字段时自动创建了唯一索引。

    您可以通过 mongodb 命令删除索引:

    db.pets.dropIndex( { "cat" : -1 } )
    

    阅读更多here

    或者通过mongoose,像这样(你需要改变它以适应你的项目)

    var Driver = mongoose.model('admins', DriverSchema);
    // Dropping an Index in MongoDB
    Driver.collection.dropIndex('Username', function(err, result) {
        if (err) {
            console.log('Error in dropping index!', err);
        }
    });
    module.exports = Driver;
    

    【讨论】:

    • 感谢您的回复,我确实修改了您提供的代码,如下所示:Admin.collection.dropIndex('Username', function(err, result) { if(err) console.log('Error ind dropping index!', err) console.log(result) }) 其中“Admin”是猫鼬模型。当我运行代码时,我收到错误消息:Error in dropping index! MongoError: index not found with name [Username] errmsg: 'index not found with name [Username]', code: 27, codeName: 'IndexNotFound', [Symbol(mongoErrorContextSymbol)]: {}
    • @UPrashanth 索引名称是 Username_1 而不是 Username。在代码中更改它应该可以工作
    猜你喜欢
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2018-07-08
    • 1970-01-01
    相关资源
    最近更新 更多