mongoose - 蒙哥错误: E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null }

标签 mongoose mobile collections duplicates key

我创建了一个用户模式,其中有一个移动字段。移动字段应该是唯一的,但仍然允许空值,并且应该只将唯一性与字符串进行比较。这是我的调试信息:

我的用户模式中的“移动” key

mobile: {
  type: String,
  index: {
    unique: true,
    partialFilterExpression: { mobile: { $type: 'string' } }
  },
}

Mongoose 调试日志

Mongoose: users.createIndex({ mobile: 1 }, { unique: true, partialFilterExpression: { mobile: { '$type': 'string' } }, background: true})

错误

MongoError: E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null }
    at Function.create (~/project/node_modules/mongodb/lib/core/error.js:44:12)
    at toError (~/project/node_modules/mongodb/lib/utils.js:150:22)
    at ~/project/node_modules/mongodb/lib/operations/common_functions.js:265:39
    at handler (~/project/node_modules/mongodb/lib/core/sdam/topology.js:971:24)
    at ~/project/node_modules/mongodb/lib/core/sdam/server.js:496:5
    at ~/project/node_modules/mongodb/lib/core/connection/pool.js:420:18
    at processTicksAndRejections (internal/process/task_queues.js:75:11) {
  driver: true,
  name: 'MongoError',
  index: 0,
  code: 11000,
  keyPattern: { mobile: 1 },
  keyValue: { mobile: null },
  errmsg: 'E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null }',
  [Symbol(mongoErrorContextSymbol)]: {}
}

我尝试了很多选项和来自 stackoverflow 的不同答案,但似乎没有任何效果,所以我想问问正确的方法。

编辑

问题是我的代码是正确的,但我必须删除并重新创建表才能正常工作。另一种解决方案是只删除索引。

最佳答案

问题是我的代码是正确的,但我必须删除并重新创建表才能正常工作。另一种解决方案是只删除索引。

关于mongoose - 蒙哥错误: E11000 duplicate key error collection: users index: mobile_1 dup key: { mobile: null },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62169061/

相关文章:

arrays - 在 NodeJS 中向数组 mongoose 中插入元素创建对象

html - 如何在没有媒体查询的情况下让我的文本换行的同时制作两个 div 堆栈

javascript - jQuery:移动设备的 keyup 事件

asp.net - 使用 ASP.NET,如何创建 iPhone/Android 特定的移动网站?

java - 清空一个 ArrayList 还是只创建一个新的并让旧的被垃圾收集?

java - 最快的集合包含 5-10 个整数的方法

javascript - 使用 mongoose 保存嵌套对象(数组),在 mongodb 中结果为空对象

javascript - nodejs查询数据和代码组织

javascript - Mongoose : "TypeError: "监听器“参数必须是一个函数”连接

C# .NET 和直接对象集合