Mongoose searching FindOne with multiple arguments

All we need is an easy explanation of the problem, so here it is.

My first attempt at building something with Angular + express + mongodb, so I’m probably going about this completely the wrong way. Express is being used to serve up json. Angular then takes care of all the views etc.

I’m using Mongoose to interact with Mongo.

I have the following database schema:

var categorySchema = new mongoose.Schema({
  title: String, // this is the Category title
  retailers : [ 
    {
      title: String,  // this is the retailer title
      data: {       // this is the retailers Data
        strapLine: String,
        img: String ,  // this is the retailer's image
        intro: String,
        website: String,
        address: String,
        tel: String,
        email: String
      } 
    }
  ]
});

var Category = mongoose.model('Category', categorySchema);

and in Express I have a couple of routes to get the data:

 app.get('/data/categories', function(req, res) {
   // Find all Categories.
   Category.find(function(err, data) {
     if (err) return console.error(err);
     res.json(data)
   });
 });


 // return a list of retailers belonging to the category
 app.get('/data/retailer_list/:category', function(req, res) {
   //pass in the category param (the unique ID), and use that to do our retailer lookup
   Category.findOne({ _id: req.params.category }, function(err, data) {
     if (err) return console.error(err);
     res.json(data)
   }); 
 });

The above works – I’m just having big problems trying to get at a single retailer. I’m passing the category, and retailer id through… I’ve tried all sorts of things – from doing a find on the category, then a findOne on the contents within… but I just cant get it to work. I’m probably going about this all wrong…

I found this thread here: findOne Subdocument in Mongoose and implemented the solution – however, it returns all my retailers – and not just the one I want.

// Returns a single retailer
app.get('/data/retailer_detail/:category/:id', function(req, res) {
  //pass in the category param (the unique ID), and use that to do our retailer lookup
 Category.findOne({_id: req.params.category , 'retailers.$': 1}, function(err, data) {
    console.log(data);
    if (err) return console.error(err);
    res.json(data)
  }); 
});    

Thanks,
Rob

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Now that I see your full filter/query, you should be able to use the array positional operator in this case as part of the projection rather than doing client side filtering:

app.get('/data/retailer_detail/:category/:id', function(req, res) {
  //pass in the category param (the unique ID), and use that to do our retailer lookup
 Category.findOne({
    /* query */
    _id: req.params.category , 
    'retailers._id' : req.params.id
  },
  {  /* projection */
     "retailers.$" : 1 
  }, 
  function(err, data) {
  var retailer = _.where(data.retailers , { id : req.params.id });
    if (err) return console.error(err);
    res.json(retailer)
  }); 
}); 

For the { "retailers.$" : 1 } to work properly, the query must include a field from an element in the array. The $ operator returns the first match only.

Method 2

The guys next door use Mongo + Express and gave me some pointers: they explained to me how mongo worked, and advised I should use underscore.js to assist with my filter.

They said I needed to pull the entire category out – and then run the filter. I don’t strictly need , ‘retailers._id’ : req.params.id} but they said to leave it in as it guaranteed that the category would only be returned if an item within it contained that information. I still don’t really know why or how… So can’t really mark this as solved.. it it solved, but I don’t really get why as yet – so will do more reading 🙂

app.get('/data/retailer_detail/:category/:id', function(req, res) {
  //pass in the category param (the unique ID), and use that to do our retailer lookup
 Category.findOne({_id: req.params.category , 'retailers._id' : req.params.id}, function(err, data) {
  var retailer = _.where(data.retailers , { id : req.params.id });
    if (err) return console.error(err);
    res.json(retailer)
  }); 
}); 

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply