1

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

and it returns a JSON that looks like this to my react front end.

{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"), 
"email" : "[email protected]", 
"quantite" : 1, 
"matricule" : 1}

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" : "[email protected]", 
    "quantite" : 1, 
    "matricule" : 1}

3 Answers 3

2

give this a try. it will serialize string ids without objectid stuff.

    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);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

there you go! yup that fixed the issue, thank you so much.
but it does come with a slight hitch , each key is in its own json, instead of one with all the keys, but theres a work around for that thankfully.
0

Fixed by creating a class for the mongodb object.

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

get them and deserialize with 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;
}

return them on request :

[HttpGet]
public async Task<string> ShowProductsAsync()
{
    MongodbModel model = new MongodbModel();
    var products = await model.getAllProducts();
    Console.WriteLine(products);
    return JsonConvert.SerializeObject(products);
}

Comments

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

2 Comments

It would be great if you explain OP what you have done in this code.
LOL, excluding the _id is not an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.