gpt4 book ai didi

mongodb-.net-driver - MongoDB C# - 如何将任意 JSON 文档保存为动态类型?

转载 作者:行者123 更新时间:2023-12-03 02:15:26 25 4
gpt4 key购买 nike

我正在尝试编写一个通用 Web Api Controller ,它允许我将 JSON 文档保存到集合中,而无需指定 C# 类型。我尝试将代码压缩为要点:

public class PassThroughController : ApiController
{
[Route("api/mongodb/{collection}")]
public void Post(string collection, dynamic document)
{
const string connectionString = "mongodb://localhost";

var client = new MongoClient(connectionString);
var db = client.GetServer().GetDatabase("SampleDb");
var mongoCollection = db.GetCollection(collection);

mongoCollection.Save(document,
new MongoInsertOptions
{
WriteConcern = WriteConcern.Acknowledged
});
}
}

我正在尝试发布一个简单的文档:

{ id: "2112", name: "Rush" }

但是无论我向该方法发送什么内容,我都会收到类似于以下内容的错误:“Save can only be used with Documents that has an Id.”

我们尝试了许多不同的 Id 属性(Id、id、_id),但它们都会导致类似的问题。

有什么想法吗?

谢谢

最佳答案

在同事的帮助下,我找到了一个解决方案:

public class PassThroughController : ApiController
{
[Route("api/mongodb/{collection}")]
public void Post(string collection, HttpRequestMessage message)
{
const string connectionString = "mongodb://localhost";

var client = new MongoClient(connectionString);
var db = client.GetServer().GetDatabase("SampleDb");
var mongoCollection = db.GetCollection(collection);

var json = message.Content.ReadAsStringAsync().Result;
var document = BsonSerializer.Deserialize<BsonDocument>(json);

mongoCollection.Save(document,
new MongoInsertOptions
{
WriteConcern = WriteConcern.Acknowledged
});
}
}

关于mongodb-.net-driver - MongoDB C# - 如何将任意 JSON 文档保存为动态类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25536306/

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