从在 C# 中序列化为 JSON 的 mongodb 文档中删除 ObjectId [英] Remove ObjectId from mongodb document serialized to JSON in C#
问题描述
我在这里遇到了一些问题.我正在使用此功能从 mongodb 集合中获取我的所有产品:
I'm having a bit of an issue here. I am getting all my products from a mongodb collection with this function:
public async Task<string> getAllProducts()
{
List<string> all = new List<string>();
var document = await getCollection("produits").Find(new BsonDocument()).ToCursorAsync();
foreach (var doc in document.ToEnumerable())
{
var res = doc.ToJson();
all.Add(res);
}
return JsonConvert.SerializeObject(all);
}
它向我的 React 前端返回一个看起来像这样的 JSON.
and it returns a JSON that looks like this to my react front end.
{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"),
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}
问题是我无法在我的 javascript 中解析它,因为:ObjectId("5e49bdf5f040e808847a17d7")
problem is i cant parse this in my javascript because of this : ObjectId("5e49bdf5f040e808847a17d7")
当然我可以在解析它之前做一些字符串魔术,但是在服务器端更正它.那么有没有办法摆脱这个问题并得到这样的结果?
Of course I could do some string magic before I parse it, but id rather it be corrected on the server side. So is there a way I can get rid of this problem and get a result like this?
{ "_id" : "5e49bdf5f040e808847a17d7",
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}
推荐答案
通过为 mongodb 对象创建一个类来修复.
public class Product
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int matricule { get; set; }
public int quantite { get; set; }
public string email { get; set; }
public float prix { get; set; }
public string image { get; set; }
}
获取它们并使用 BsonSerializer 反序列化:
public async Task<List<Product>> getAllProducts(){
var collection = await getCollection("produits").Find(new BsonDocument()).ToListAsync();
List<Product> all = new List<Product>();
foreach(var doc in collection){
all.Add(BsonSerializer.Deserialize<Product>(doc));
}
return all;
}
应要求归还:
[HttpGet]
public async Task<string> ShowProductsAsync()
{
MongodbModel model = new MongodbModel();
var products = await model.getAllProducts();
Console.WriteLine(products);
return JsonConvert.SerializeObject(products);
}
这篇关于从在 C# 中序列化为 JSON 的 mongodb 文档中删除 ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!