Home > Mobile >  Get object has array of object in asp.net api mongodb
Get object has array of object in asp.net api mongodb

Time:10-01

i want to get all Carts object in mongodb but the result is missing the list of items

sample data mongodb:

{
  "_id": "temp",
  "total": "2300000",
  "buyer": "test",
  "items": [
    {
      "name": "IP-8",
      "amount": "2",
      "price": "20000"
    },
    {
      "name": "IP-12",
      "amount": "2",
      "price": "20000"
    }
  ]
}

Result:

[{"id":"temp","buyer":"test","total":2300000}]

here are 2 class:

public class Carts
{
    [BsonId]
    public string Id { get; set; }
    public string buyer { get; set; }
    public double total { get; set; }
    [BsonElement("items")]
    List<CartItem> items { get; set; }

}

public class CartItem
{
    [DataMember]
    public string name { get; set; }

    [DataMember]
    public int amount { get; set; }

    [DataMember]
    public double price { get; set; }
}

function class:

public class TempCartService
{
    private readonly IMongoCollection<Carts> _temp;
    //private readonly IMongoCollection<CartItem> _items
    public TempCartService(IOptions<ShopDbSetting> options)
    {
        var mongoClient = new MongoClient(options.Value.ConnectionString);
        _temp = mongoClient.GetDatabase(options.Value.DatabaseName)
            .GetCollection<Carts>("Carts");
    }
    public async Task<List<Carts>> FindAll() =>
      await _temp.Find(_ => true).ToListAsync();
}

CodePudding user response:

please change your accessible modifier to public see the below code

public class Carts
{
    [BsonId]
    public string Id { get; set; }
    public string buyer { get; set; }
    public double total { get; set; }
    [BsonElement("items")]
    public List<CartItem> items { get; set; }

}

public class CartItem
{
    [DataMember]
    public string name { get; set; }

    [DataMember]
    public int amount { get; set; }

    [DataMember]
    public double price { get; set; }
}
  • Related