首页 > 解决方案 > 在 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}

标签: c#jsonreactjsmongodbparsing

解决方案


试试这个。它将序列化字符串 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);
    }

推荐阅读