【问题标题】:mongodb 3.4.2 InvalidIndexSpecificationOption error: The field 'unique' is not valid for an _id index specificationmongodb 3.4.2 InvalidIndexSpecificationOption 错误:字段“唯一”对于 _id 索引规范无效
【发布时间】:2017-07-11 16:59:31
【问题描述】:

命令 db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} ) 在 mongo 版本 3.4.2 上失败,但不是 3.2.11。 mongo 文档表明 3.4 版同时支持 uniquebackground 属性。

Mongo 3.4.2 失败 ...

> use testDB
switched to db testDB
> db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} )
{
    "ok" : 0,
    "errmsg" : "The field 'unique' is not valid for an _id index specification. Specification: { ns: \"testDB.testCollection\", v: 1, key: { _id: 1.0 }, name: \"_id_2\", unique: true, background: true }",
    "code" : 197,
    "codeName" : "InvalidIndexSpecificationOption"
}
> 

Mongo 3.2.11 工作...

> use testDB
switched to db testDB
> db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 1,
    "note" : "all indexes already exist",
    "ok" : 1
}
> 

有人知道解决方法吗?

我们正在使用 Mongoose Node.js 包装器来创建 Mongo 索引,因此不能添加 uniquebackground 属性。

干杯!

埃德

【问题讨论】:

  • 如何解决这个问题?

标签: mongodb mongoose mongodb-indexes


【解决方案1】:

我在使用 sinon.stub 编写测试用例来调用函数时也发生了这个错误。 原因是,我在存根函数时传递了错误的数据。

代码 - (错误代码)

const accountstub = sinon.stub(accountservice, "getall");

accountstub.callFake(()=> accountmockdata)

已解决

const accountstub = sinon.stub(accountservice, "getall");

accountstub.callFake(()=> [accountmockdata])

解决方案 - 它期待一个对象数组,而我只传递了该对象。 如果您在数据库中使用索引,请确保我传递的是正确的。

您可以通过在开发环境中运行来控制数据,然后查看函数返回的数据类型(对象、数组等)并将相同的数据粘贴到您的模拟文件中。

【讨论】:

    【解决方案2】:

    在mongodb3.4中,_id字段不支持unique和background,其他字段可以。

    【讨论】:

      【解决方案3】:

      唯一性在这里不是问题.. _id,已经有索引(自动创建),而您不能创建第二个索引,它具有与第一个完全相同的字段 (_id:1) .

      使用 _id 以外的其他字段进行测试怎么样,您会发现唯一性和背景是可能的,只要该字段不存在索引即可。

      【讨论】:

      • 谢谢 J.Jussi,就是这样。我没有理解 3.2.11 中指出冗余索引请求的注释。既然你已经指出了这一点,那就太明显了。
      • @JJussi - 您对索引 { _id: -1 } 的建议是什么,以支持逆序排序。没有必要吗?
      • 不,没有必要,因为 mongodb 可以同时使用索引。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2017-04-06
      相关资源
      最近更新 更多