【问题标题】:Mongoose Schema array can be the same over multiple documentsMongoose Schema 数组可以在多个文档中相同
【发布时间】:2021-10-21 01:15:06
【问题描述】:

我有以下架构设置:

//character.js in models/character.js
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
const CharacterSchema  = new mongoose.Schema({
    // defines the character name
    name: {
        type  : String
    },
    // list of the mission ids
    missionList: [ Number ]
});
const Character= mongoose.model('Character', CharacterSchema);
module.exports = Character;

我可以创建新角色并将它们存储在数据库中。我还在数据库中存储了一些可以通过 id 找到的任务。角色应该只有一个 id 数组,以免重复具有多个角色的任务。任务架构如下所示:

//mission.js in models/mission.js
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true);
const MissionSchema  = new mongoose.Schema({
    // defines the mission name
    name: {
        type  : String,
        required : true
    },
    // defines the id of the current mission
    id: {
        type: Number,
        required : true
    }
});
const Mission = mongoose.model('Mission', MissionSchema);
module.exports = Mission;

现在,当我创建一个角色时,它工作正常,但是当我在missionList 数组中创建具有相同值的第二个角色时,它会引发以下错误:

(node:18) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: space-test.character index: missionList.name_1 dup key: { missionList.name: null }

这是我创建角色的方法:

var char1 = new Character({ name: "Bambi", missionList: [0, 1, 2, 3, 4, 5, 6, 7]}; 
char1.save();// working fine

var char2 = new Character({ name: "R2D2", missionList: [0, 1, 2, 3, 4, 5, 6, 7]}; 
char2.save();// throwing the error

我在使用我的猫鼬模式时错了吗?我没有将任务列表声明为唯一的,因此它们应该有可能在多个字符中是相同的。

任何建议或帮助如何解决这个问题?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在某个时候,在 {"missionList.name":1} 上创建了一个唯一索引。

    您需要删除该索引以避免该错误。

    【讨论】:

    • 谢谢你让我找到答案。问题是数据库模式中保存了损坏的数据模型。我放弃了洞任务模型并重新设置它们。解决了,谢谢
    猜你喜欢
    • 2012-12-26
    • 2021-04-09
    • 2020-10-22
    • 2011-11-22
    • 2017-05-03
    • 2013-05-02
    • 2018-02-02
    • 2015-09-14
    相关资源
    最近更新 更多