【发布时间】: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”它应该是自动添加的,但如果你使用记录就不会,我确实得到了,因为如果他只是在插入数据库之前更改值就没有设置,这很有意义,这是错误的处理方式,因为如果您使用记录,它就不起作用。