Home > Net >  Get Method does not find document (MongoDb) even if it exists
Get Method does not find document (MongoDb) even if it exists

Time:01-05

I have the following get-method:

public async Task<TModel> Get(string id)
{
    var filter = Builders<TModel>.Filter.Eq("_id",id);
    var result = await _collection.FindAsync(filter);
    return result.FirstOrDefault();
}

My Model is defined like this:

public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    ...
}

If I test this method I get 404 (Not found) back.

What I already checked:

  1. The id parameter has the right id.
  2. Used id exists in database.
  3. _collection is the correct IMongoCollection.
  4. MongoDB server is running and collection exits.
  5. Connection string, credentials and permissions to connect to the MongoDB server is correct (other crud methods are working).

What other troubleshooting steps can I do? What could be the error?

Thank you for your help!

CodePudding user response:

In the Entity class the _id field is defined to be ObjectId, but in the Get function it is string. MongoDB matches are type-sensitive, so you'll need to convert the string to an ObjectId first.

  • Related