【问题标题】:java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]java.lang.IllegalArgumentException:BasicBSONList 只能使用数字键,而不是:[_id]
【发布时间】:2013-09-27 19:51:59
【问题描述】:

在另一张 SO 海报(Vinicius Miana)解决我的issue 以插入List[DBObject] ...

// Bulk insert all documents
collection.insert(MongoDBList(docs)) // docs is List[DBObject]

现在,我在尝试插入时看到此错误。

java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]

编辑

完整的堆栈跟踪

[info]   java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]
[info]   at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:161)
[info]   at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:152)
[info]   at org.bson.types.BasicBSONList.get(BasicBSONList.java:104)
[info]   at com.mongodb.DBCollection.apply(DBCollection.java:767)
[info]   at com.mongodb.DBCollection.apply(DBCollection.java:756)
[info]   at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:220)
[info]   at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:204)
[info]   at com.mongodb.DBCollection.insert(DBCollection.java:76)
[info]   at com.mongodb.casbah.MongoCollectionBase$class.insert(MongoCollection.scala:508)
[info]   at com.mongodb.casbah.MongoCollection.insert(MongoCollection.scala:866)

我已经检查了 post 与我完全相同的问题,但我不确定如何应用已接受的答案。

此错误是否意味着我无法插入任何键值对,使得 value 不能转换为 Int(根据 BasicBSONList)?

【问题讨论】:

    标签: scala casbah


    【解决方案1】:

    您根本无法将MongoDBList 插入集合中。如果你想在一个操作中插入多个文档,你只需将你的List[DBObject] 直接传递给insert 方法:

    collection.insert(docs: _*)
    

    _* 是必需的,因为insert 是一个可变参数方法。

    另一方面,我不得不承认这个异常在这里相当混乱,它的错误信息与实际问题并没有太大关系。我怀疑这是因为 Casbah 试图将 MongoDBList 视为可以插入数据库的常规文档。它尝试访问它尝试插入并导致异常的对象的_id

    【讨论】:

    【解决方案2】:

    Salat作者在这里。 Ghik 是正确的:您的问题是您将模型对象包装在虚假的 MongoDBList 中。此外,您似乎将模型对象直接提供给您的收藏。如果要这样做,则需要在插入之前手动序列化每个对象。

    我会推荐这种方法是不必要的!这是你需要做的。让 SalatDAOModelCompanion 工作 - 请参阅 https://github.com/novus/salat/wiki/SalatDAOhttps://github.com/novus/salat/wiki/SalatWithPlay2

    这是一个名为 MyObject 的模型对象的 SalatDAO 示例实现:

    object MyObjectDAO extends SalatDAO[MyObject, ObjectId](collection = MongoConnection()("my_test_db")("my_test_coll"))
    

    然后只需使用 SalatDAO#insert(docs: Traversable[ObjectType], wc: WriteConcern = defaultWriteConcern) 插入您的文档

    MyObjectDAO.insert(docs)
    

    【讨论】:

      【解决方案3】:

      MongoDBList 与普通列表不同,它是BasicDBList 的便捷包装器,因此无法按预期转换为 vargs。

      你应该提供List[DBObject] 然后爆炸成vargs:

      val docs = List[DBObject("a" -> "b")
      collection.insert(docs: _*)
      

      【讨论】:

        猜你喜欢
        • 2013-05-12
        • 2016-02-26
        • 2015-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 2019-10-08
        • 1970-01-01
        相关资源
        最近更新 更多