Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique index not working with Mongoose / MongoDB

I've got a problem with creating unique indexes using Mongoose / MongoDb and can't get it to work. I'm able to add two documents with the same attribute values when I have set a unique index.

I've tried everything I can think of - restarting (everything) changing the syntax etc.

Code

Addtion >>

This is the method that I'm using to save an entity:

  create  : function(entity, definition, successFn, errorFn){

    var model = mongoose.model(entity);
    newModel = new model(definition);

    newModel.save(function(error) {
      if(error){
        if(!errorFn){
          throw error;
        }
        errorFn(newModel);
        return;
      }

      successFn(newModel);
    });
  }...

<<

var Something = new Schema({
  objectId          : ObjectId,
  name              : { type : String, index: { unique: true }}, 
  url               : { type : String, index: { unique: true }},
...etc
mongoose.model('Something', Something);

Mongo output

 [conn1] insert xxxxx.agencies 1526ms
 [conn1] building new index on { name: 1 } for xxxxx.agencies
 [conn1] insert xxxxx.system.indexes exception 11000 E11000 duplicate key error    index: xxxxx.agencies.$name_1  dup key: { : "something" } 4ms
 [conn1] building new index on { url: 1 } for xxxxx.agencies
 [conn1] insert xxxxx.system.indexes exception 11000 E11000 duplicate key error index: xxxxx.agencies.$url_1  dup key: { : "http://www.something.com" } 1ms

When I checked in MongoHub the indexes don't appear, so they don't look like they have been created.

This is a duplicate of this question, but it doesn't have an answer that works for me.

like image 922
Lewis Avatar asked May 08 '11 18:05

Lewis


People also ask

Why is unique not working in mongoose?

For uniqueness to be ensured, mongo needs to create its index. Make sure that before you create any users, its index is already created.

Does MongoDB support unique indexes?

MongoDB creates a unique index on the _id field during the creation of a collection.

How do I create a unique compound index in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

What does unique do in mongoose?

The unique option tells Mongoose that each document must have a unique value for a given path. For example, below is how you can tell Mongoose that a user's email must be unique. const mongoose = require('mongoose'); const userSchema = new mongoose.


1 Answers

one solution that doesn't involve erasing your db, is to remove any duplicates manually, then run something along the lines of:

db.users.ensureIndex({email:1},{unique:true,sparse:true});

from the mongo shell

like image 66
Victor Powell Avatar answered Sep 25 '22 02:09

Victor Powell