簡體   English   中英

MongoDB:刪除唯一約束

[英]MongoDB: remove unique constraint

我正在嘗試“使用帶有 Express 和 Mongoose 的 Node.js 開發 RESTful API”示例,但遇到了 MongoDB 架構的問題:

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" }',

模式定義中有一個獨特的約束:

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

我該如何擺脫它? 當我刪除 unique: true 並重新啟動應用程序時,架構不會更新。

mongodb 如何處理模式的“更改”?

“mongodb 如何處理對架構的“更改”?”

MongoDB 是無模式的

唯一強制執行的唯一事情是在索引級別,您可以在其中定義具有唯一條件的集合的索引。 因此,您可能希望刪除相關索引並在必要時重新創建它。

我希望這會有所幫助

db.collection_name.getIndexes()

返回一個數組,其中包含標識和描述集合中現有索引的文檔列表。 現在從列表中找到您的索引名稱,然后刪除該索引,如下所示

db.users.dropIndex("your_index_name_here")

當您向 mongoose 模式添加唯一約束時,將在同一鍵上創建索引。 例如:如果您有一個名為style的模式鍵,那么將創建一個索引作為style_1 即使您修改架構,已創建的索引仍將存在。 您需要刪除此索引以重置唯一約束。

如果您安裝了 mongoDB Compass,那么您可以轉到 collection->indexes 並刪除它。 Atlas Web 界面上也提供了相同的界面。 就我而言,我在鍵url上有一個索引,我已將其刪除。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM