0

I have create two data models and try to apply different query on it using mongoDb C# driver. Here is the query in a get method

var res = _postCollection.Aggregate().Lookup("_commentCollection", "Comments", "_id", "result").ToList();
return OK(res)

But when I call the method from postman get the following result

System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonObjectId' to type 'MongoDB.Bson.BsonBoolean'.
   at get_AsBoolean(Object )
   at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)
...............
Hridoy_089
  • 318
  • 3
  • 11

3 Answers3

0

Your problem is casting! You want to try cast the object type "MongoDB.Bson.BsonObjectId" to type "MongoDB.Bson.BsonBoolean". This is not possible and you will receive an exception

ABlue
  • 664
  • 6
  • 20
0

The parameter for the Lookup are Ref

string foreignCollectionName,
FieldDefinition<TResult> localField,
FieldDefinition<TForeignDocument> foreignField,
FieldDefinition<TNewResult> as,
AggregateLookupOptions<TForeignDocument, TNewResult> options

so the localField and foreignField must be of the same type. In your case they are of different type clearly shown in the error

System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonObjectId' to type 'MongoDB.Bson.BsonBoolean'.
   at get_AsBoolean(Object )
   at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)

Here is the similar question on SO which can help you.

शेखर
  • 17,412
  • 13
  • 61
  • 117
0

You forgot to set the generics to Lookup()

var res = _postCollection.Aggregate().Lookup<ResultType, Comment>("_commentCollection", "Comments", "_id", "result").ToList();