FMR
FMR

Reputation: 303

Query MongoDB in C# by MongoDBRef

I'm trying to get all Photos of an User, querying by it's UserId reference. (I know about embedded documents in Mongo, but this is how I'd like to use it).

Here is the error I get: "System.InvalidOperationException: '{UserId.$id}.ToString() is not supported'"

public ICollection<Photo> GetAllUserPhotos(string userId)
{
  var photos = _photos.Find(photo => photo.UserId.Id.ToString() == userId);
  var photoListTest = photos.ToList() // here I get the error
  return photoListTest;
}

A "normal" query like this works without problems:

public List<User> GetAllUsers() => _users.find(user => true).ToList();

Here are my models:

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

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

        public MongoDBRef UserId { get; set; }
    }

Upvotes: 1

Views: 2415

Answers (1)

mickl
mickl

Reputation: 49985

The problem here is that .Find() method takes Expression<T,bool> as parameter and then when you hit .ToList() MongoDB driver tries to convert such expression into MongoDB query / aggregation language. MongoDB .NET driver doesn't understand {UserId.$id}.ToString() and therefore you're getting an exception.

To fix it you should try the other way around - convert your variable in-memory to a type that's stored in the database, try:

var userIdConverted = ObjectId.Parse(userId); // or use string if it's string in your database 
var dbRef = new MongoDBRef("colName", userIdConverted); 
var photos = _photos.Find(photo => photo.UserId.Id.ToString() == dbRef );

Upvotes: 2

Related Questions