Mongoose schema: 'unique' not being respec

2019-01-20 17:06发布

问题:

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
    }
]

回答1:

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')


回答2:

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.