0

Medicine model field :

var field = {
    genericName: {type: String, select: true, index: true},
    brandName: {type: String, select: true, index: true},
    manufacturer: {type: String, select: true},
    distributor: {type: String, select: true},
}

FavoriteMedicine model field :

var field = {
    emrId: {type: Schema.Types.ObjectId},
    medicine: {type: Schema.Types.ObjectId, ref: 'Medicine'}
}

The route caller :

localhost:3131/api/v0.1/medicine/56e6944c824b78110040c234/favorite/all?search=foobar

The query :

var re = req.query.search ? new RegExp('^' + req.query.search + '.*$', 'i') : '';

FavoriteMedicine.find()
    .or([
        { 'medicine.genericName': { $regex: re }}, { 'medicine.brandName': { $regex: re }},
        { 'medicine.manufacturer': { $regex: re }}, { 'medicine.distributor': { $regex: re }}
    ])
    .where({emrId:req.params.emr_id})
    .populate({path:'medicine', model:Medicine})
    .exec(function (err, meds) {
        if(err){ res.status(500).json(err); return; };
        res.send(meds)
    })

Result :

[]

I am expecting this to return the match of the search params or if search params is absent it should return all the entry.


Meanwhile on my other code:

On my other search query where I search directly on first level fields from the Medicine Model

var re = req.query.search ? new RegExp('^' + req.query.search + '.*$', 'i') : '';

Medicine.find().or([
        { 'genericName': { $regex: re }}, { 'brandName': { $regex: re }},
        { 'manufacturer': { $regex: re }}, { 'distributor': { $regex: re }}
    ])
    .exec(function (err, meds) {
        if(err){ res.status(500).json(err); return; };
        res.send(meds)
    })

Result (working fine):

if route is /medicine/all it returns all list if route is /medicine/all?search=paracetamol it returns all the matching query from genericName or brandName or manufacturer or distributor.


What am I missing from my first query on FavoriteMedicine?

jofftiquez
  • 7,548
  • 10
  • 67
  • 121
  • 1
    `"medicine"` is a "reference" containing an `ObjectId` and not the actual data. This is **not a JOIN**. So `.populate()` can contain "query" arguments on the populated items, **however** this does not affect the master selection and **all** `FavoriteMedicine` will be returned, regardless of whether the populated condition matches or not. Just with `null` after the population. You can "post filter" after population to remove the `null` lookups, but this is still "not a JOIN". Duplicate around here somewhere. – Blakes Seven Mar 29 '16 at 03:16
  • @BlakesSeven very helpful thanks for the explanation. I will post a working answer based on the solution from the link. – jofftiquez Mar 29 '16 at 03:40
  • No you won't. That's why your question was put on hold. We don't need duplicate questions and responses everywhere. – Blakes Seven Mar 29 '16 at 03:44

0 Answers0