c# - 在 C# 中从序列化为 JSON 的 mongodb 文档中删除 ObjectId
问题描述
我这里有点问题。我正在使用此功能从 mongodb 集合中获取我的所有产品:
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);
}
它向我的反应前端返回一个看起来像这样的 JSON。
{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"),
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}
问题是我无法在我的javascript中解析它,因为:ObjectId("5e49bdf5f040e808847a17d7")
当然,我可以在解析它之前做一些字符串魔术,但我宁愿在服务器端更正它。那么有没有办法可以摆脱这个问题并得到这样的结果?
{ "_id" : "5e49bdf5f040e808847a17d7",
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}
解决方案
试试这个。它将序列化字符串 id 而没有 objectid 的东西。
public static async Task<string> getAllProducts()
{
var collection = db.GetCollection<object>("produits");
var all = new List<object>();
using (var cursor = await collection.FindAsync("{}"))
{
while (await cursor.MoveNextAsync())
{
foreach (var doc in cursor.Current.ToArray())
{
all.Add(doc);
}
}
}
return Newtonsoft.Json.JsonConvert.SerializeObject(all);
}
推荐阅读
- vba - 使用“FormulaR1C1”时如何解决错误 1004
- vba - 在 Visio 中运行私有子
- ruby-on-rails - 带有 sidekiq 的导轨,比赛条件
- .net - SDL2 仅在 winforms 面板上呈现
- tensorflow - 在微控制器上调用 Failed() Tensorflow Lite
- angular - NodeSass - 用来自另一个 json 的值覆盖来自 json 的值
- javascript - 使用 D3.JS 将 HTML 标签添加到轴标签
- python-3.x - 与 DeepDiff 的比较
- hibernate - JPA:可以在查询中获取项目的偏移量
- dart - 为什么双减法会产生意想不到的结果 - Dart