如何使用 F# 和 MongoDB 处理不存在的(可选)字段
How to deal with non-existent (optional ) fields with F# and MongoDB
我已经设法很容易地将数据序列化为类型。
let coll = db.GetCollection<PostDataItem>("postItems")
我遇到的问题是,当架构更改时,数据将无法正确序列化为类型,因为数据库中不存在该数据。我收到错误:
MongoDB.Bson.BsonSerializationException: 'No matching creator found.'
我不能使用 F# 选项类型,因为它仍然需要一个值 - 但是有没有办法使用标准 .Net 驱动程序来序列化数据,其中字段存在于类型中但可能尚不存在于数据库中.我希望它默认为 null 或 None 但不想更改数据库中的每条记录。
我的类型定义如下所示:
type PostDataItem = {
_id: BsonObjectId
dateLodged: DateTime
productCode: string
productDescription: string
clientReference: string
manifestContract: string
client: string
quantity: string
unitPrice: string
gst: string
total: string
clientReference2: string
weight: string
reference1: string
ticketNumber: string
transactioncode: string
invoiceExplanationField1: string
invoiceExplanationField2: string
invoiceExplanationField3: string
invoiceExplanationField4: string
invoiceExplanationField5: string
invoiceExplanationField6: string
orderNumberToCheck: string
isUnique: Nullable<bool>
expectedPrice: Nullable<decimal>
想法?
您可以使用 BsonDefaultValue
属性:
open MongoDB.Bson.Serialization.Attributes
type MyType =
{
[<BsonDefaultValue("MyDefaultValue")>]
MyNewField : string
}
(默认值必须是编译时常量,所以如果你想要一个可选字段的默认值,你必须使用 null
而不是 None
。)
或者,您可以将整个类型标记为 CLIMutable
,然后缺少的字段将根据其类型自动设置为自然默认值:
[<CLIMutable>]
type MyType =
{
MyNewField : string // will automatically default to null
}
我已经设法很容易地将数据序列化为类型。
let coll = db.GetCollection<PostDataItem>("postItems")
我遇到的问题是,当架构更改时,数据将无法正确序列化为类型,因为数据库中不存在该数据。我收到错误:
MongoDB.Bson.BsonSerializationException: 'No matching creator found.'
我不能使用 F# 选项类型,因为它仍然需要一个值 - 但是有没有办法使用标准 .Net 驱动程序来序列化数据,其中字段存在于类型中但可能尚不存在于数据库中.我希望它默认为 null 或 None 但不想更改数据库中的每条记录。
我的类型定义如下所示:
type PostDataItem = {
_id: BsonObjectId
dateLodged: DateTime
productCode: string
productDescription: string
clientReference: string
manifestContract: string
client: string
quantity: string
unitPrice: string
gst: string
total: string
clientReference2: string
weight: string
reference1: string
ticketNumber: string
transactioncode: string
invoiceExplanationField1: string
invoiceExplanationField2: string
invoiceExplanationField3: string
invoiceExplanationField4: string
invoiceExplanationField5: string
invoiceExplanationField6: string
orderNumberToCheck: string
isUnique: Nullable<bool>
expectedPrice: Nullable<decimal>
想法?
您可以使用 BsonDefaultValue
属性:
open MongoDB.Bson.Serialization.Attributes
type MyType =
{
[<BsonDefaultValue("MyDefaultValue")>]
MyNewField : string
}
(默认值必须是编译时常量,所以如果你想要一个可选字段的默认值,你必须使用 null
而不是 None
。)
或者,您可以将整个类型标记为 CLIMutable
,然后缺少的字段将根据其类型自动设置为自然默认值:
[<CLIMutable>]
type MyType =
{
MyNewField : string // will automatically default to null
}