1

My User collection model schema:

var userModel = new Schema({
    userAddress: { type: Object, ref: 'useraddress' },
    name: String,
});

My User addresses collection model schema:

var addressModel = new Schema({
    macAddress: String,
    repeat: Number,
});

Get data method is:

module.exports.get = function (req, res) {
var _repeatTime = 2;
var _searchQRY = [];
_searchQRY.push(
    {
        "useraddress.repeat": { $gte: _repeatTime}
    });
userModel.find({ $and: _searchQRY }).populate('useraddress').exec(function (err, results) {
        res.json({ record: results})
    });

This is my code. I want to filter with address repeat number. But i am not getting correct result with this query.

Hardik Mandankaa
  • 3,129
  • 4
  • 23
  • 32

1 Answers1

0

First Mongoose performs the the search on users collection by {"useraddress.repeat": {$gte: val}} query. And only after the call starts population.

So you should get 0 results as address is not yet populated.

Here are 2 ways of solving this. First, check out this answer please. You'll need to:

//Any conditions that apply to not populated user collection documents
var userQuery = {};
userModel.find(userQuery)
 //Populate only if the condition is fulfilled
 .populate('useraddress', null, {"useraddress.repeat": { $gte: _repeatTime}})
 .exec(function (err, results) {
  results = results.filter(function(doc){
   //If not populated it will be null, so we filter them out
   return !!doc.useraddress;
  });

  //Do needed stuff here.
 });

The second way is to use aggregation and $lookup (you'll need mongodb v 3.2+). Basically it means to move this population and filtering to DB level.

userModel
 .aggregate()
 //Anything applying to users collection before population
 .match(userQuery)
 .lookup({
  from: 'address', //Please check collection name here
  localField: 'useraddress',
  foreignField: '_id',
  as: 'useraddress'
 })
 //Lookup pushes the mathes to an array, in our case it's 1:1, so we can unwind
 .unwind('useraddress')
 //Filter them as you want
 .match({'useraddress.repeat': { $gte: _repeatTime}})
 .exec(function (result) {
  //Get the result here.
 });
Community
  • 1
  • 1
Antonio Narkevich
  • 4,206
  • 18
  • 28