首页 > 解决方案 > 字段“_id”上的 BSON 数据类型“Null”无效

问题描述

在与此问题类似的情况下,我正在尝试 LiteDB 文档中的示例,并在运行时收到错误:

Invalid BSON data type 'Null' on field '_id'.

我的代码如下,包括我解决问题的尝试,即添加从github 上的评论中提取的 _id 和 Id 声明,here

Public Class Customer
   Public _id As LiteDB.BsonValue
   Public Id As Integer
   Public Name As String
   Public Phones As String
   Public IsActive As Boolean
End Class

Public Class ThisAddIn


  Shared Sub testSub()
    Dim db As New LiteDB.LiteDatabase(Directory.GetCurrentDirectory() & "\DEPDB.db")
    Dim col As LiteDB.LiteCollection(Of Customer)

    col = db.GetCollection(Of Customer)("customer")

    Dim tCustomer As New Customer

    tCustomer.Id = 1
    tCustomer.Name = "John Doe"
    tCustomer.Phones = "12354534"
    tCustomer.IsActive = True

    col.Insert(tCustomer)
  end sub
end class

标签: vb.netlitedb

解决方案


将类声明稍微更改为:

Public Class Customer
  Public Property Id As Integer
  Public Property Name As String
  Public Phones As String
  Public IsActive As Boolean
End Class

允许代码编译和运行,并且“名称”字段可以使用以下内容进行搜索:

    col.EnsureIndex(Function(x) x.Name)

    Dim tresult = col.FindOne(Function(x) x.Name.Contains("Jo"))

    MsgBox(tresult.Name)

我完全偶然地遇到了这个解决方案,在声明中添加了一些文字......任何解释都将不胜感激。


推荐阅读