I have a MongoDB as my database and the backend is written in node.js. I am trying to implement a search for a table which returns me all results with the string entered AND string matching.
For example searching "foo" will return (In that order)
foo maker moo
doo foo doo //The order of word search does not matter as long as it puts the word search first
foobar
fooboo
Currently I have this but I am convinced there is a better way to do it without searching the db twice:
async function(req, res) {
var customerName = req.params.customerName;
//word match
var customers1 = await Models.DummyContactTable.find({
customerName: {
$regex: "^" + customerName,
$options: 'i'
},
IsActive: true
});
//String match
var customers2 = await Models.DummyContactTable.find({
$and: [
{
customerName: {
$regex: customerName, $options: 'i'
}
},
{
customerName: {
$not: {
$regex: "^" + customerName,
}
},
IsActive: true
}
]
});
//Since sometimes we get duplicates, doing a filter and find to de-dup
var customers = customers1.concat(customers2.filter((customer) => !customers1.find(f => f.uuid === customer.uuid)));