mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

New Mongoose and new Mongodb WiredTiger storage engine unique:true not working

Open mithralaya opened this issue 11 years ago • 4 comments

Hello Mongoose team,

Versions I am using

MongoDB: 3.0.1 with --storageEngine wiredTiger enabled
Mongoose: 4.0.1

The model I am trying to make it work

var Basket = new mongoose.Schema({
    _id: {type: mongoose.Schema.ObjectId, default: mongoose.Types.ObjectId, index: true},
    basketId: {type: Number, unique:true, require:true, index: true},
    storeId: {type: Number, require:true, index: true},
    consumerId: {type: Number, require:false, index: true}
});

module.exports = mongoose.model('Basket', Basket);

Note: basketId is marked as unique:true with index enabled

I have a brand new install of new mongoDB with wiredtiger.

No DB created nor records.

When I try to insert duplicates it inserts to the DB. unique: true does not work.

Please help with this error. I suspect my code is right. Please let me know if anything is wrong in my code.

Many thanks, Karthik

mithralaya avatar Apr 08 '15 16:04 mithralaya

Just an idea: Try without _id definition. This is done by mongoose.

Just another question about your schema: For what is basketId, storeId and consumerId used? Are they also schemas?

Swissbite avatar Apr 08 '15 16:04 Swissbite

basketId is the only primary key. Please treat storeId and consumerId as just a searchable fields.

Thank for your help. Let me try without _id.

mithralaya avatar Apr 08 '15 16:04 mithralaya

Thank you so much. It works without the _id definition.

Many thanks, Karthik

mithralaya avatar Apr 08 '15 17:04 mithralaya

Yeah MongoDB creates an _id index by default - mongoose's index build will fail if you attempt to create an index on _id that doesn't match what's in mongodb by default. For future reference, I'd recommend you listen to MyModel.on('index', function(err) {}) event for index errors - it'll report any index failures

vkarpov15 avatar Apr 08 '15 18:04 vkarpov15