繁体   English   中英

从在 C# 中序列化为 JSON 的 mongodb 文档中删除 ObjectId

[英]Remove ObjectId from mongodb document serialized to JSON in C#

我这里有点问题。 我正在使用此功能从 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);
        }

它向我的 React 前端返回一个看起来像这样的 JSON。

{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"), 
"email" : "example@gmail.com", 
"quantite" : 1, 
"matricule" : 1}

问题是我无法在我的 javascript 中解析它,因为: ObjectId("5e49bdf5f040e808847a17d7")

当然,我可以在解析它之前做一些字符串魔术,但是 id 而是在服务器端对其进行更正。 那么有没有办法摆脱这个问题并得到这样的结果?

{ "_id" : "5e49bdf5f040e808847a17d7", 
    "email" : "example@gmail.com", 
    "quantite" : 1, 
    "matricule" : 1}

试试这个。 它将序列化没有 objectid 的字符串 id。

    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);
    }

通过为 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);
}
string GetAllProduits(){
    var collection = database.GetCollection<BsonDocument>("produits");
    var project = Builders<BsonDocument>.Projection.Exclude("_id");
    var filter = Builders<BsonDocument>.Filter.Empty;
    var rlt=collection.Find(filter).Project(project);
    return rlt.ToList().ToJson();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM