1

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; }
    }
4
  • Images instead of code in a post will cost votes, which in turn make it likely no one will even look at the question. Commented Mar 23, 2020 at 17:19
  • @JoelCoehoorn thank you for letting me know, and for the downvote. I'm editing it now. But could you provide a reason for this, since I was not aware. Commented Mar 23, 2020 at 17:29
  • Back from lunch. Wasn't my downvote; just cluing into why it was probably there. But there are many reasons not to use images, other than actually getting an answer and that it's actually easier on your end to just paste the code: meta.stackoverflow.com/a/285557/3043 Commented Mar 23, 2020 at 18:30
  • Thank you @JoelCoehoorn. I actually chose an image to emphasize the place where it crashed (an unusual one in my opinion), code was not much, only a few lines. But indeed, I never thought of the other downsides. Commented Mar 23, 2020 at 19:47

1 Answer 1

2

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 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.