【发布时间】: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
我在使用我的猫鼬模式时错了吗?我没有将任务列表声明为唯一的,因此它们应该有可能在多个字符中是相同的。
任何建议或帮助如何解决这个问题?
【问题讨论】: