Search code examples
node.jsmongoosemongoose-schema

Use a filter in a Mongoose JS find() function that includes an object


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?


Solution

  • 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.