0

Why mongoose return empty results for an ObjectId that exists?

mongoose run this query which getting empty results.

const c = await Category.find({ subCategories: { '$in': [ { _id: mongoose.Types.ObjectId("5ccdc3dd4e88235af8923c62") } ] } });
console.log({ c });

mongoose response:

Mongoose: categories.find({ subCategories: { '$in': [ { _id: ObjectId("5ccdc3dd4e88235af8923c62") } ] } }, { projection: {} })
{ c: '[]' }

In my database there is results for this ObjectId...

enter image description here

Model definition:

 const Category = mongoose.model(
    'Category',
    new mongoose.Schema({
      name: { type: String },
      subCategories: [
        {
          name: { type: String }
        }
      ]
    })
  );
Jon Sud
  • 10,211
  • 17
  • 76
  • 174
  • 1
    `.find({ 'subCategories._id': "5ccdc3dd4e88235af8923c62" })`. You use ["Dot Notation"](https://docs.mongodb.com/manual/core/document/#dot-notation) for accessing nested properties. Providing a "whole object" means looking for an **exact match** of that whole object ( meaning here the `_id` property **only** ) which is usually not the case. Also mongoose "autocasts" string values to their defined schema types in anything but `aggregate()` queries. And `$in` is used for a "list of arguments", and NOT to "query a list element" as you appear to have confused it with. – Neil Lunn May 04 '19 at 22:19
  • 1
    I strongly suggest taking the time to read and practice the examples from [MongoDB CRUD Operations](https://docs.mongodb.com/manual/crud/) in the core documentation. Reading *all of that* should give you enough understanding of the query and update basics of MongoDB and should save you a lot of questions. I would certainly recommend understanding the basics before writing any more code in your application. – Neil Lunn May 04 '19 at 22:23

0 Answers0