gpt4 book ai didi

c# - MongoDB : documents with variable structure using and C#

转载 作者:行者123 更新时间:2023-11-30 22:04:48 24 4
gpt4 key购买 nike

我有一个 HTML 表单,可以创建具有动态结构的文档。以下是用户插入的一些数据示例。

一个非常简单的文档

{
"name" : "Simple element",
"notes" : "Lorem ipsum rocks",
"values" : [
{
"name" : "An array with 2 values",
"value" : [ 100,200],
"editable" : true
}
]

和更复杂的文档

{
"name" : "Complex element",
"notes" : "Lorem ipsum rocks",
"values" : [
{
"name" : "A text value",
"value" : "ABCDEF",
"editable" : true
},
{
"name" : "A numeric value",
"value" : 100,
"editable" : false
},
{
"name" : "A array of 4 values",
"value" : [1,2,3,4],
"editable" : false
},
{
"name" : "A matrix 2x4",
"value" : [[1,2,3,4],[5,6,7,8]],
"editable" : false
}
]

文档必须使用 C# MongoCharp 驱动程序和 NancyFX 保存在 MongoDB 中。目前 POST 是以这种方式实现的,但我不确定这是否是处理具有动态结构的对象的正确方法

Post["/api/docs"] = _ =>
{
//looking for better solution
var json = Request.Body.AsString();
var item = BsonDocument.Parse(json);
database.GetCollection("docs").Insert(item);
return new Response { StatusCode = HttpStatusCode.Created };
};

但是对于GET方法找不到好的解决方案

Get["/api/docs"] = _ =>
{
//looking for solution
};

您认为这种情况的最佳解决方案是什么?

最佳答案

还有另一种方法可以解决这个问题。我们称它为“强类型解决方案”。我创建了两个 POCO 对象

public class DocumentItem
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public String Id { get; set; }

public String Name { get; set; }

public String Notes { get; set; }

public SubItem[] Values { get; set; }

}

public class SubItem
{
public String Name { get; set; }

public Boolean Editable { get; set; }

public Object Value { get; set; }
}

在模块中读取数据的实现如下所示

    Get["/api/docs/{id}"] = p => database.GetCollection<DocumentItem>("docs")
.FindOne(Query<DocumentItem>.EQ(x => x.Id, (string)p.id));

Get["/api/docs"] = _ => database.GetCollection<DocumentItem>("docs")
.FindAll()
.ToList();

我可以用这种方式对插入使用绑定(bind)

   Post["/api/docs"] = _ =>
{
var item = this.Bind<DocumentItem>();
database.GetCollection("docs").Insert(item);
return item;
};

关于c# - MongoDB : documents with variable structure using and C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24882902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com