插入多个值时"E11000 duplicate key error collection"猫鼬错误



我正试图将一些数据导入MongoDB,并一直遇到这个错误。

MongoBulkWriteError: E11000 duplicate key error collection: MyDB.clist_list index: clients.email_1 dup key: { clients.email: null }

型号:

interface Client {
name: string;
email: string;
}
interface Agent {
pipedrive_id: number;
name: string;
clients?: Array<Client>;
}
const clientSchema = new Schema<Client>({
name: { type: String, required: true },
email: {
type: String,
trim: true,
lowercase: true,
unique: true,
validate: {
validator(str: string) {
return /^w+([\.-]?w+)*@w+([\.-]?w+)*(.w{2,3})+$/.test(str);
},
message: 'Please enter a valid email',
},
required: [true, 'Email required'],
},  
});
const agentSchema = new Schema<Agent>({
pipedrive_id: { type: Number, required: true },
name: String,
clients: [clientSchema],
});
const AgentClients = model<Agent>('client_list', agentSchema);

正如您在模型上看到的,客户端集合是可选的。此外,每次运行DB都会被移除(删除(并完全创建(只是为了测试目的,这样就没有遗留的索引或其他什么(。

这是有效载荷。

[
{
first_name: 'Jen Test',
pipedrive_id: 2186,
clients: []
},
{
name: 'Carl Test',
pipedrive_id: 2191,
clients: []
}
]

这是让我困惑的部分。在没有Clients的情况下,email怎么会有null的重复值???

我在Model上使用insertMany方法来插入数据(如果这有任何帮助的话(。

我知道在这个问题上有很多类似的问题,但没有一个是我的具体问题。

您在clientSchemaemail属性上指定了unique: true。由于您的两个输入都没有指定email,MongoDB将假定它是null

所以你在那里有冲突。一方面您指定email必须是唯一的,另一方面您试图插入两个具有相同emailnull的文档。

如果希望保持email字段的唯一性,同时允许null值,则应检查稀疏索引。

在您的模式中,您应该传递额外的属性sparse: true

相关内容

最新更新