简体   繁体   English

f#使用记录在MongoDB上插入

[英]f# Insert on MongoDB using Records

I've been trying for a while to insert on MongoDB using only records with no success. 我已经尝试了一段时间,仅使用没有成功的记录在MongoDB上插入。

My problem is that I want to create a simple insert function which I send a generic type and it is inserted into the database. 我的问题是我想创建一个简单的插入函数,然后将其发送一个通用类型并将其插入数据库中。

Like so. 像这样

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

From this function, I tried inserting the following records. 通过此功能,我尝试插入以下记录。

// 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
}

So does anyone can think of a solution for this or am I stuck having to use a class. 有人能想到这个解决方案吗?还是我不得不使用类。

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

Also, does anyone has any Idea of why when the C# MongoDB library translates the mutable he gets the property with the @ at the end? 而且,有人对C#MongoDB库为什么转换可变变量时会在末尾使用@取得属性有任何想法吗? I would be fine with having all my properties set as mutable, although this wouldn't be my first choice, having he create multiple properties on the DB is quite bad. 我将所有属性设置为可变的就可以了,尽管这不是我的首选,但是让他在数据库上创建多个属性是非常糟糕的。

You could try annotating your records with CLIMutable (and no mutable fields). 您可以尝试使用CLIMutable (并且没有mutable字段)来注释记录。

The @ s end up in the DB because MongoDB using reflection and F# implementing mutable with backing fields fieldName@ @最终出现在数据库中,因为MongoDB使用反射和F#实现具有后备字段fieldName@ mutable fieldName@

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM