0

My model looks like this:

  {
    visibleIn: { order: false, showcase: true, search: true },
    _id: qijjdjrby0ytnaznj2dk,
    name: 'iPhone 7 + Black, Grey, or Rose-Gold',
    __v: 0
  }

I named this model Product, so const Product = require('../path/to/file'). I'm trying to find all Products that have an order of true when I use the find() method. I thought something like this would have worked:

Product.find({visibleIn.order: true});

Results in Unexpected token '.' error

or

Product.find({visibleIn: {order: true}});

Results in an empty array []

So how do I use a filter if it's inside another object?

  • 1
    Check out this [question](https://stackoverflow.com/questions/16002659/how-to-query-nested-objects) – Saeed Apr 11 '20 at 15:40
  • as mentioned above ^ the solution is to use a string for the key: `Product.find({visibleIn.order: true});` should be: `Product.find({'visibleIn.order': true});` I haven't tested it, but I've used it before in my own code, give it a try and let us know – nax3t Apr 13 '20 at 19:12
  • nax3t, it works! – ScrunchyNaut Apr 13 '20 at 23:04

2 Answers2

1
Product.find({visibleIn.order: true});

have you tried this? you can use this to filter your DB

  • 4
    Please add some explanation to your answer such that others can learn from it – Nico Haase Apr 12 '20 at 12:27
  • 1
    I have tried that. To answer Nico Haase's request, the reason for the code above is because objects can be written as two notations: `object.property` and `object['property']`. Both will call `property`. – ScrunchyNaut Apr 13 '20 at 22:56
0

Thanks to nax3t for answering my question (but did so in a comment, so don't ding me for answering the question). Instead of

Product.find({visibleIn.order: true}); 

I need to use

Product.find({'visibleIn.order': true});

This is because of the way Mongoose passes object arguments to itself.