0

I have Book objects in my mongoDb that look like this (very simplified):

{
  "_id": ObjectId("620e341dbf575892d9396dc2"),
  "title": "my title",
  "author": {
    "_id": ObjectId("620e341dbf575892d9396dd4"),
    "surname": "My surname"
  }
}

I'm trying to query and get all books by an author, and so far I've tried:

const booksByAuthor = await Book.find({ author: { _id: "620e341dbf575892d9396dd4" } });

and

const booksByAuthor = await Book.find({ 'author._id': "620e341dbf575892d9396dd4" } );

But in no case I'm getting the existing books from the given author, and I'm only getting empty arrays.

What am I doing wrong?

1
  • Your second attempt should work. I would guess the issue is somewhere in the details you have not shown. Commented Feb 20, 2022 at 21:00

1 Answer 1

2

The problem for 1st query:

When you want to query in a nested field you have to use dot notation as you do in the second query.
The problem to not use dot notation is mongo match the entire object (even the fields order) so is not a good way... you can check simple examples like:

  • This one: The object is found because the object is exactly the same.
  • Another this one where the object has the same fields and values from two objects in the collection but... querying using an object the order matters, so only returns one.

The problem for 2nd query:

I think the problem here is you are matching string vs ObjectId. The syntaxis is correct (dot notation) but when mondo match the values one of them is string and another is ObjectId.

So you can try this query:

const booksByAuthor = await Book.find({ 'author._id': mongoose.Types.ObjectId("620e341dbf575892d9396dd4") } );

Check this example with your query, matching string and ObjectId none result is returned, but parsing string to ObjectId... magic appears

Sign up to request clarification or add additional context in comments.

3 Comments

OP is using mongoose, which will cast the string to ObjectId automatically, so that's not the issue here.
Yes, you're absolutely right! Thank you!
Despite using mongoose this returns the desired result. I mean the solution by J.F. solves the problem. I'm not sure if I was missing something before, though.

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.