Sails.js & MongoDB: duplicate key error index

I use Sails.js (0.9.8) and MongoDB (via the sails-mongo adapter) to create a set of pages that can be arranged in a tree view. I would like to save the page path in a UUID array

My model:

module.exports = { schema: true, attributes: { uuid: { type: 'string', unique: true, required: true, uuidv4: true }, name: { type: 'string', required: true, empty: false }, path: { type: 'array', required: true, array: true } } } 

This works well when I save the root page (the path property has only one element because it is the root page. This is what it saved in MongoDB:

 { _id: ObjectId("52f853e9609fb6c0341bdfcc"), createdAt: ISODate("2014-02-10T04:22:01.828Z"), name: "Home Page", path: [ "a2b23e1f-954b-49a3-91f1-4d62d209a093" ], updatedAt: ISODate("2014-02-10T04:22:01.833Z"), uuid: "a2b23e1f-954b-49a3-91f1-4d62d209a093" } 

But when I want to create a โ€œsubpageโ€ below my previous created page (Home / Products), I get this error:

MongoError: E11000 Duplicate Key Error Index: cms-project.item. $ path_1 dup key: {: "a2b23e1f-954b-49a3-91f1-4d62d209a093"}

Here are the data I sent:

 { name: 'Products', uuid: 'a004ee54-7e42-49bf-976c-9bb93c118038', path: [ 'a2b23e1f-954b-49a3-91f1-4d62d209a093', 'a004ee54-7e42-49bf-976c-9bb93c118038' ] } 

I probably missed something, but I donโ€™t know what. If I store the path in a string instead of an array, it works fine, but I find it much less elegant and convenient.

0
source share
1 answer

Not sure about all parts of Sails / Waterline since I never played with it. But by mistake there is a problem: there is a unique index in the field of your array.

When you insert your second document, you already have one of the values โ€‹โ€‹(parent) in the path field in the other document. The only restriction will not allow this. Most likely, for what you model, you do not want this, and the index cannot be unique.

I hope that you yourself have installed this under the assumption that this means uniqueness in the array contained in the document. If you have done this, you know where to look and what to change now. If this is automatically deployed in some way, then I'm not the one to help.

Change the index so that it is not unique. You can confirm this through the mongo shell:

 use cms-project db.item.getIndices() 

Good luck.

+3
source

All Articles