Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: remove unique constraint

Tags:

I'm trying the "Develop a RESTful API Using Node.js With Express and Mongoose" example and I ran into a problem with the 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" }', 

there is a unique contraint in the schema definition:

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

how do I get rid off that? When I remove unique: true and restart the app, the schema doesn't get updated.

How does mongodb handle "alters" to the schema?

like image 645
Stefan Ernst Avatar asked Sep 09 '12 07:09

Stefan Ernst


People also ask

What is ensureIndex in MongoDB?

In the MongoDB to create an index, the ensureIndex() method is used. Syntax: db.collection_name.ensureIndex( {KEY:1, KEY:2} ) Here in the above syntax, the key is a field name that you want to make an index and it will be 1 and -1 to make it on ascending or descending order.

What is the difference between unique index and unique constraint?

A unique index ensures that the values in the index key columns are unique. A unique constraint also guarantees that no duplicate values can be inserted into the column(s) on which the constraint is created. When a unique constraint is created a corresponding unique index is automatically created on the column(s).

Is null unique in MongoDB?

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field.

How do I get unique records in MongoDB?

In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.


1 Answers

"How does mongodb handle "alters" to the schema?"

MongoDB is schema-less

The only thing there uniqueness is enforced is on the indexing level where you can define indexes on a collection with unique criteria. So you may want to remove the related index and re-created it if necessary.

like image 188
Andreas Jung Avatar answered Sep 18 '22 23:09

Andreas Jung