Sails.js & MongoDB: duplicate key error index

谁说我不能喝 提交于 2019-12-12 02:33:55

问题


I'm using Sails.js (0.9.8) and MongoDB (via the sails-mongo adaptor) to create a collection of pages that can be positioned in a tree-view. I would like to store the path of a page in an array of UUIDs

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

It works well when I save a 'root' page (the 'path' property has just one item because it's a root page. Here is what it was 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 Page/Products), I get this error:

MongoError: E11000 duplicate key error index: cms-project.item.$path_1 dup key: { : "a2b23e1f-954b-49a3-91f1-4d62d209a093" }

Here is 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 work well, but I find it much less elegant and handy.


回答1:


Not sure of all the Sails / Waterline parts myself as I've never played with it. But by the error the problem is there is a unique index on your array field.

When you are inserting your second document, you already have one of the values (the parent) in your path field in another document. The unique constraint is not going to allow this. Most certainly for what you are modelling, you do not want this and the index cannot be unique.

I hope that you set this up yourself under the assumption that it meant unique within the array contained in the document. If you did then you know where to look and what to change now. If this is being automatically deployed somehow, then I'm not the one to help.

Change the index to not be unique. You can confirm this through the mongo shell:

use cms-project
db.item.getIndices()

Good luck



来源:https://stackoverflow.com/questions/21669381/sails-js-mongodb-duplicate-key-error-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!