跨文档的数组元素上的MongoDB唯一索引(不跨嵌套文档) [英] MongoDB Unique Index on array element across documents (not across nested document)
问题描述
我有一个架构如下:
Schema = mongoose.Schema
User= new Schema
{ name: String,
phones: [
{
confirmed: {
type: Boolean,
default: false
},
number: {
type: String,
unique: true
}
]}
这应该不允许使用相同的电话号码创建 2 个文档.我知道索引在数组元素中不能是唯一的,所以我可以在嵌套文档中有 1 个具有 2 个相同数字的文档,但我不希望 2 个文档具有相同的数字.未创建索引.我检查了可能不允许创建索引的现有重复文档,但没有.我尝试使用
This was supposed not to allow creation of 2 documents with same phone number. I understand that the index cant be unique across array elements so i am fine of having 1 document with 2 same numbers in the nested document but i dont want 2 documents to have same number. The index is not being created. I checked for existing duplicate documents that might be not allowing the index to be created but there is not. I tried creating the index in atlas with
{ "phones.number": 1 }, {unique:true}
{ "phones.number": 1 }, {unique:true}
它根本没有创建它
推荐答案
为此,您需要更改一些内容.
To do this you need to change a few things.
首先,您的架构必须是这样的 index
:
First of all, your schema has to be an index
like this:
number: {
type: String,
index: true, // <-- This line
unique: true
}
并且,在您的连接选项中添加 useCreateIndex: true
.例如,我有:
And, in your conections option add useCreateIndex: true
. For example, I have:
const mongooseOpts = {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
useCreateIndex: true //<-- This line
};
await mongoose.connect(uri, mongooseOpts);
然后,当您尝试添加重复的电话号码时,将引发错误.
Then, when you try to add a duplicate number phone an error will be thrown.
BulkWriteError: E11000 重复键错误 dup key: { : 1";}
BulkWriteError: E11000 duplicate key error dup key: { : "1" }
通过这两个步骤,如果也不起作用,请尝试删除collection
并重新创建.
With these two steps, if also didn't work, try removing the collection
and creating again.
这篇关于跨文档的数组元素上的MongoDB唯一索引(不跨嵌套文档)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!