【问题标题】:f# Insert on MongoDB using Recordsf# 使用记录在 MongoDB 上插入
【发布时间】:2017-11-17 16:03:53
【问题描述】:

我一直在尝试仅使用记录在 MongoDB 上插入,但没有成功。

我的问题是我想创建一个简单的插入函数,我发送一个泛型类型并将它插入到数据库中。

像这样。

let insert (value: 'a) = 
    let collection = MongoClient().GetDatabase("db").GetCollection<'a> "col"
    collection.InsertOne value

通过这个函数,我尝试插入以下记录。

// Error that it can't set the Id
type t1 = {
    Id: ObjectId
    Text: string
}
// Creates the record perfectly but doesn't generate a new Id
type t2 = {
    Id: string
    Text: string
}
// Creates the record and autogenerates the Id but doesn't insert the Text, and there are two Ids (_id, Id@) 
type t3 = {
    mutable Id: ObjectId
    Text: string
}
// Creates the record and autogenerates the Id but for every property it generates two on MongoDB (_id, Id@, Text, Text@)
type t4 = {
    mutable Id: ObjectId
    mutable Text: string
}

那么有没有人能想到一个解决方案,还是我不得不使用一个类。

// Works!!!
type t5() = 
    member val Id = ObjectId.Empty with get, set
    member val Name = ""  with get, set

另外,有没有人知道为什么当 C# MongoDB 库翻译可变变量时,他会在末尾获得带有 @ 的属性? 我可以将所有属性设置为可变属性,尽管这不是我的第一选择,让他在数据库上创建多个属性非常糟糕。

【问题讨论】:

  • 您使用的是哪个驱动程序? .NET 驱动程序?有点混淆您在这里问的内容,并尝试弄清楚您是否尝试将 ObjectId 值自动分配给存储为 "Id" 的字段,或者您的意思是 "_id" 无论如何都会自动添加。
  • 我正在使用默认的 MongoDB C# 驱动程序。 docs.mongodb.com/ecosystem/drivers/csharp我的意思是“_id”它应该是自动添加的,但如果你使用记录就不会,我确实得到了,因为如果他只是在插入数据库之前更改值就没有设置,这很有意义,这是错误的处理方式,因为如果您使用记录,它就不起作用。

标签: mongodb f#


【解决方案1】:

您可以尝试使用 CLIMutable 注释您的记录(并且没有 mutable 字段)。

@s 最终在数据库中,因为 MongoDB 使用反射和 F# 实现 mutable 和支持字段 fieldName@

【讨论】:

  • 我认为使用 CLIMutable 与将我的所有属性设置为可变的一样,但事实证明并非如此。它仍然不适用于我的情况,MongoDB 驱动程序将 ID 保留为空。我真的在这里航行未知水域,因为我没有看到任何其他 f# 开发人员面临与我相同的问题。猜猜每个人都在做我现在正在做的事情,使用在与 C# 库交互时效果很好的类。感谢您的帮助。
  • 看起来这篇博文展示了medium.com/@mukund.sharma92/…
猜你喜欢
  • 2011-07-05
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
相关资源
最近更新 更多