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?
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.
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).
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.
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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With