MongoDB:删除唯一约束

Ste*_*nst 13 mongodb database-schema node.js

我正在尝试"使用带有Express和Mongoose的Node.js开发RESTful API"示例,我遇到了MongoDB Schema的问题:

POST: 
{ title: 'My Awesome T-shirt 2',
  description: 'All about the details. Of course it\'s black.',
  style: '12345' }
{ [MongoError: E11000 duplicate key error index: ecomm_database.products.$style_1  dup key: { : "12345" }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: ecomm_database.products.$style_1  dup key: { : "12345" }',
Run Code Online (Sandbox Code Playgroud)

模式定义中有一个独特的约束:

var Product = new Schema({  
    title: { type: String, required: true },  
    description: { type: String, required: true },  
    style: { type: String, unique: true },  
    modified: { type: Date, default: Date.now } });
Run Code Online (Sandbox Code Playgroud)

我怎么摆脱那个?当我删除unique:true并重新启动应用程序时,架构不会更新.

mongodb如何处理"改变"架构?

小智 10

"mongodb如何处理"改变"模式?"

MongoDB是无架构的

唯一强制执行的是在索引级别,您可以使用唯一条件在集合上定义索引.因此,您可能希望删除相关索引并在必要时重新创建它.

  • 那很有效.供参考:>使用ecomm_database> db.products.dropIndexes(); {"nIndexesWas":2,"msg":"为集合删除了非_id索引","ok":1} (10认同)
  • “MongoDB 是*无模式*”……那么,为什么他们的文档中有一个关于模式设计的完整部分呢?http://www.mongodb.org/display/DOCS/Schema+Design (2认同)
  • 我的生命已经消失了三个小时,但是非常感谢您的发现。db.users.dropIndexes(); def为我工作。 (2认同)

Ane*_*eed 9

当您向猫鼬模式添加唯一约束时,将在同一键上创建索引。例如:如果您有一个名为 的架构键style,则索引将创建为style_1. 即使您修改架构,已创建的索引仍然存在。您需要删除该索引才能重置唯一约束。

如果您安装了 mongoDB Compass,那么您可以转到集合->索引并删除它。Atlas Web 界面上也提供相同的界面。就我而言,我在 key 上有一个索引url,我已将其删除。

在此输入图像描述


Man*_*ana 5

我希望这会有所帮助

db.collection_name.getIndexes()
Run Code Online (Sandbox Code Playgroud)

返回一个数组,其中包含标识和描述集合中现有索引的文档列表。现在从列表中找到您的索引名称,然后删除该索引,如下所示

db.users.dropIndex("your_index_name_here")
Run Code Online (Sandbox Code Playgroud)