【问题标题】:Allow nested array in a document to share identical objects with other docs in collection允许文档中的嵌套数组与集合中的其他文档共享相同的对象
【发布时间】:2021-06-02 09:19:35
【问题描述】:

我有一个如下所示的选项列表架构:

const PicklistSchema = mongoose.Schema({
    list_name: {
        type: String,
        required: true,
    },
    author_id: {
        type: String,
        required: true,
    },
    author_name: {
        type: String,
        required: true,
    },
    items: {
        type: Array,
        required: true,
        default: [],
    },
    status: {
        type: String,
        enum: [
            'initialized',
            'submitted',
            'retrieving',
            'retrieved',
            'complete',
        ],
        required: true,
        default: 'initialized',
    },
    date: {
        type: Date,
        required: true,
        default: Date.now(),
    },
});

插入“items”数组的对象如下所示:

{
    "name": "testitem1",
    "size": "00",
    "desc": "This item should only be used in a dev environment, for testing purposes",
    "upcs": [ "testitem1", "test" ],
    "id": "test"
}

我创建了一个新的选择列表并添加了测试项目,它可以工作。如果我创建第二个选项列表并尝试添加相同的测试项目,我会得到:

E11000 duplicate key error collection: picklists.picklists index: items.id_1 dup key: { items.id: "test" }

如果我尝试创建一个新的选项列表而不向第一个选项添加任何内容,错误将是 { items.id: null }

我尝试将unique: false 添加到 items 数组和其他几个选项(例如编写 items 数组的子模式并制作 id: { type: String, unique: false }),但没有什么能阻止该错误。我正在阅读稀疏索引,但我不确定这是否是解决方案,如果是,如何将其合并到代码中。

如何让 mongo 对每个选项列表文档的 items 数组中的内容不那么固执己见?

我可以删除集合中的每个选项列表,如果我创建的第二个(或第三个等)选项列表尝试添加第一个选项列表中包含的项目,则会出现错误。

【问题讨论】:

    标签: mongodb mongoose duplicates schema unique


    【解决方案1】:

    看起来很多类似的错误是由架构先前对数据强加的集合中的伪影引起的,并且通过删除集合并创建一个新集合来解决,所以我尝试了,它成功了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多