Mongodb唯一稀疏索引

标签 mongodb indexing mongoose unique sparse-matrix

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

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 }

但是,如果我插入第二个文档且未设置 key ,则会收到此错误:

{ [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 }

有什么提示吗?

最佳答案

我也刚刚遇到这个问题。我想要一个值要么为空,要么是唯一的。因此,我设置了 uniquesparse 标志:

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

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

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

(所以,这与此处的问题相同:mongo _id field duplicate key error)

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

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

因此,如果您也遇到此问题,请确保您没有设置默认值,并确保您没有在代码中的其他任何地方将值设置为 null。相反,如果您需要显式设置它,请将其设置为未定义(或唯一值)。

关于Mongodb唯一稀疏索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125089/

相关文章:

node.js - 在 mongodb 中使用聚合与 $group

mysql - 提高大表查询的性能?

javascript - 使用 Mongoose 保存

sql - 针对特定值生成索引

mysql - SQL跨表索引的方法?

node.js - 无法通过 Mongoose 保存的 Express 访问 POST 调用中的数据

jquery - Mongoose 插入\u0000

mongodb - 我正在尝试连接到mongodb Atlas,但我不断收到错误消息,无法继续

node.js - 根据类型 y 分组的字段 x 的前 1 个返回 mongoDB 中的记录

python - 在要插入 mongodb 的字典列表中设置唯一字段