1

I'm trying to use Mongoose with this schema

var RestoSchema = new Schema({
    "qname"          : {type: String, required: true, unique: true},
    ...
});

The problem is that this still permits new entries to the database to be created with an existing qname. From what i can see below the index has been created, but without any demonstrable impact when I use the .save method. What am I misunderstanding?

> db.restos.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "ns" : "af.restos",
        "name" : "_id_"
    },
    {
        "v" : 1,
        "key" : {
            "qname" : 1
        },
        "ns" : "af.restos",
        "name" : "qname_1",
        "background" : true,
        "safe" : null
    }
]
Simon H
  • 20,332
  • 14
  • 71
  • 128

2 Answers2

2

The getIndexes output shows that the index on qname wasn't created as a unique index. Mongoose doesn't alter an existing index, so you'll have to manually drop the index and then restart your app so that Mongoose can re-create it as unique.

In the shell:

db.restos.dropIndex('qname_1')
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Thanks, but now it does not create a new index when I restart the app. Even added `index:true` to the list of properties for `qname` – Simon H Jun 21 '15 at 16:04
  • 1
    See http://stackoverflow.com/questions/12452865/mongoose-not-creating-indexes for some tips on debugging that. – JohnnyHK Jun 21 '15 at 16:26
0

ByronC's response here seems to have solved it for me. I even tried dropping the collection and recreating and it still didn't work until I used the node.js NPM plugin called "mongoose-unique-validator" which you can learn more about here.

That said, the weird thing is that my unique index worked up until a schema change that implemented the "uuid" plugin which I use now for setting the _id value. There may have been something else going on but it is working for me now so I'm moving on.

Community
  • 1
  • 1
hoekma
  • 793
  • 9
  • 19