0

I am creating a search function in my app that searches through: title, description and product manufacturers name. So far, searching with title or description works fine but it does not work when I try manufacturers name (in fact, it is the only one that uses dot notation in querying)

I have some data in DB:

title: 'GLT 488',
description: 'an item',
Manufacturer:
    { _id: 5ababaa8d1c9c006c8fd8975,
    key: 'audio-note',
    name: 'Audio Note',
    },

This is how I am using MongoDB's find function:

const regex = new RegExp(escapeRegex(req.query.search), 'gi');
q.find({
    $or: [
        {'title': regex},
        {'description': regex},
        {'Manufacturer.name': regex}
    ]
},
Juozas Rastenis
  • 265
  • 3
  • 9
  • 1
    And the query is? Simply `'audio'` works fine for me. I see `_id` in the sub-key there. Using mongoose perhaps? Maybe your schema is incorrect and it interferes with the issued query. So what is the schema? On in fact is `Manufacturer` actually sitting in another collection and you use `.populate()`. Because that's what it looks like. – Neil Lunn May 07 '18 at 22:04
  • Yes I am using mongoose as it is part of KeystoneJS, is schema a db model? I do use populate, and Manufacturer comes from relationship type. – Juozas Rastenis May 07 '18 at 22:07
  • I am also using ```populate('ProductType Manufacturer')``` but it might be wrong – Juozas Rastenis May 07 '18 at 22:56
  • 1
    Yeah, you need to look at the answers on the duplicate question as shown in the large box above your question. You want to match on a regex to something that is actually in a different collection. There are different ways to do that to the simple query you tried, and that is what the existing answers explain. – Neil Lunn May 08 '18 at 00:31
  • I have looked at example and did like it's told, but it is still not working ```q.find({Manufacturer: regex}) .populate('Manufacturer', 'name') .exec(function(err, results) { if(err) { next(err); } else { locals.data.products.results = results; next(err); } }) ``` – Juozas Rastenis May 08 '18 at 13:03
  • Look harder. Look specifically for the one that does not even use `populate()` at all, but uses `$lookup` and tells you exactly what the problems with using `populate()` for this type of query are. Even the correct answers that do use `populate()` show a usage here that you still are not using. In fact all of them show different usage. – Neil Lunn May 08 '18 at 13:09

0 Answers0