Unable to cast object of type 'MongoDB.Bson.BsonArray' to type 'MongoDB.Bson.BsonBoolean'

613 views Asked by At

I am unable to return the response. Tried each and every solution available but no result. The request is passed to the controller action and action uses builders function to query mongodb. I am getting the response but unable to return in "Ok()" method. It's giving me above error.

                var builder = Builders<Campaign_Rules_Promo_Create>.Filter;

                var filter = builder.And(builder.Eq("rules.product", "flight"),
                                        builder.Eq("rules.type", flight.type),
                                        builder.Eq("rules.from_iata", flight.from_iata),
                                        builder.Eq("rules.airlines.iata", flight.airline),
                                        builder.Eq("rules.cabin", flight.cabin),
                                        builder.Eq("rules.flight_number", flight.flight_number),
                                        builder.Eq("rules.rbd_include", flight.rbd));

                var projection = Builders<Campaign_Rules_Promo_Create>.Projection.Include("rules").Exclude("_id");
                var result = _campaigns_rules_promo.Find(filter).Project(projection).ToList();


                return Ok(result);
            }
            catch (Exception ex)
            {

                throw new Exception("Error occured",ex);
            }
 public class Campaign_Check_Request_Flight
    {
        public string promo { get; set; }
        public string product { get; set; }
        public string type { get; set; }
        public string from_iata { get; set; }
        public string to_iata { get; set; }
        public string airline { get; set; }
        public string flight_number { get; set; }
        public string rbd { get; set; }
        public int adult { get; set; }
        public int child { get; set; }
        public int infant { get; set; }
        public float amount { get; set; }
        public string travel_date{ get; set; }
        public string cabin { get; set; }
        public bool registered { get; set; }
        public string device { get; set; }
        public string user_id { get; set; }
    }
public enum campaign_rules_promo_status { active, inactive }
 
    public class Campaign_Rules_Promo_Create
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string id { get; set; }
        public string campaignid { get; set; }

        public string name { get; set; }

        public string status { get; set; }

        public bool codeless { get; set; }

        public List<Schedule> schedule { get; set; }
        public List<object> rules { get; set; }
        public List<string> effects { get; set; }

        public string created_by { get; set; }

        public DateTime created_on { get; set; }

    }

here's mongodb json document

{"_id":{"$oid":"5f5a04de0128aa38ca8fb4b0"},"campaignid":"5f59ea343f42c6e124d19327","name":"PROMO INDIA 2020","status":"active","codeless":false,"schedule":[],"rules":[{"_t":"Campaign_Flights","product":"flight","type":"multi_city","from_iata":"BOM","from_city":"Mumbai","to_iata":"LHR","to_city":"London","cabin":["economy"],"airlines":[{"iata":"AI","name":"Air India"}],"flight_number":["AI634"],"rbd_exclude":[],"rbd_include":["W"]},{"_t":"Campaign_Flights","product":"flight","type":"multi_city","from_iata":"BOM","from_city":"Mumbai","to_iata":"LHR","to_city":"London","cabin":["economy"],"airlines":[{"iata":"AI","name":"Air India"}],"flight_number":[],"rbd_exclude":[],"rbd_include":["W"]},{"_t":"Campaign_Flights","product":"flight","type":"multi_city","from_iata":"BOM","from_city":"Mumbai","to_iata":"LHR","to_city":"London","cabin":["economy"],"airlines":[{"iata":"AI","name":"Air India"}],"flight_number":[],"rbd_exclude":[],"rbd_include":["W"]},{"_t":"Campaign_Flights","product":"flight","type":"one_way","from_iata":"BOM","from_city":"Mumbai","to_iata":"LHR","to_city":"London","cabin":["economy"],"airlines":[{"iata":"AI","name":"Air India"}],"flight_number":[],"rbd_exclude":[],"rbd_include":["W"]},{"_t":"Campaign_Hotels","name":"hotel booking rule 1","product":"hotel","cityid":"1234","city":"Mumbai","hotels":[{"_id":"878687","name":"Hotel Taj Mansingh"}],"star_category":[0],"blackouts":[{"from":"18:00","to":"19:00"}]}],"effects":[],"created_by":"Sudarshan","created_on":{"$date":"2020-09-11T10:07:57.238Z"}}

here's request json

{
  "promo":null,
  "product": "flight",
  "type": "multi_city",
  "from_iata": "BOM",
  "to_iata": "LHR",
  "airline": "AI",
  "flight_number":"AI634",
  "rbd":"W",
  "adult": 2,
  "child": 0,
  "infant": 1,
  "amount": 98000.00,
  "travel_date": "20-10-2020",
  "cabin":"economy",
  "registered": true,
  "device": "android",
  "user_id": "_a6hdfhkdhfdljelkrlerke"
}

Here's the stack trace exception

System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonArray' to type 'MongoDB.Bson.BsonBoolean'.
   at get_AsBoolean(Object )
   at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)
   at System.Text.Json.JsonPropertyInfo.Write(WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Thanks in advance.

2

There are 2 answers

0
phnx47 On

You tried return List<BsonDocument>, you can return Campaign_Rules_Promo_Create:

var result = _campaigns_rules_promo.Find(filter).ToList();
return Ok(result);

When you work with Projection, you should deserialize result, use BsonSerializer.Deserialize

7
phnx47 On

I checked query in my computer. I don't have Exception.

How you create _campaigns_rules_promo?

Here my example:

IMongoCollection<Campaign_Rules_Promo_Create> _campaigns_rules_promo;
var mongoUrl = MongoUrl.Create("mongodb://localhost:27017/local");
var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);
var mongoClient = new MongoClient(mongoClientSettings);
var db = mongoClient.GetDatabase(mongoUrl.DatabaseName);
_campaigns_rules_promo = db.GetCollection<Campaign_Rules_Promo_Create>("test");