本文介绍了Mongodb独特的稀疏指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的mongodb集合上创建了一个稀疏且唯一的索引。

I have created a sparse and unique index on my mongodb collection.

var Account = new Schema({
                email: { type: String, index: {unique: true, sparse: true} },
                        ....

它已被正确创建:

{ "ns" : "MyDB.accounts", "key" : { "email" : 1 }, "name" : "email_1", "unique" : true, "sparse" : true, "background" : true, "safe" : null }

但如果我插入第二个没有设置密钥的文档,我会收到此错误:

But if I insert a second document with a key not set I receive this error:

{ [MongoError: E11000 duplicate key error index: MyDB.accounts.$email_1  dup key: { : null }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: MyDB.accounts.$email_1  dup key: { : null }',
  code: 11000,
  n: 0,
  ok: 1 }

任何提示?

推荐答案

我也遇到过这个问题。我想要一个值要么是null,要么是唯一的。所以,我设置了bot h 唯一稀疏标志:

I just had this issue too. I wanted a value to either be null or be unique. So, I set both the unique and the sparse flags:

var UserSchema = new Schema({
  // ...
  email: {type: String, default: null, trim: true, unique: true, sparse: true},
  // ...
});

而且,我确保数据库实际上已经使用正确创建了索引db.users.getIndexes();

And, I made sure that the database had actually created the index correctly with db.users.getIndexes();

{
  "v" : 1,
  "key" : {
    "email" : 1
  },
  "unique" : true,
  "ns" : "test.users",
  "name" : "email_1",
  "sparse" : true,
  "background" : true,
  "safe" : null
},

(因此,与此处的问题相同:)

(So, this is not the same as the issue here: mongo _id field duplicate key error)

我的错误是设置默认值 null 。在某种意义上,Mongoose将显式 null 计为必须唯一的值。如果该字段从未定义(或未定义),则不会强制它是唯一的。

My mistake was setting the default value to null. In some sense, Mongoose counts an explicit null as a value that must be unique. If the field is never defined (or undefined) then it is not enforced to be unique.

email: {type: String, trim: true, unique: true, sparse: true},

所以,如果你也有这个问题,请确保你没有设置默认值,并确保你没有将值设置为 null 代码中的任何其他位置。相反,如果您需要明确设置它,请将其设置为 undefined (或唯一值)。

So, if you are having this issue too, make sure you're not setting default values, and make sure you're not setting the values to null anywhere else in your code either. Instead, if you need to set it explicitly, set it to undefined (or a unique value).

这篇关于Mongodb独特的稀疏指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 09:45