Searching from Both Two Fields (First Name & Last Name) in MongoDB prioritising the First Names;
Previously, The Search Results Prioritised the Last Names First, since the search was Alphabetical. Now I've Combined the Results for both but vice versa, (The Intuitive Way).
Can It be Solved Better to be more efficient or optimised, Just a newbie asking.
Suggest me a Better Search Function/Algo if you know. (Please)
globalSearch: function (q, id) {
return new Promise(async (resolve, reject) => {
q = q.toString();
q = q.trim();
var y = q.indexOf(' ') > 0;
var firstParam, secondParam;
var searchQuery, searchQuery1, searchQuery2;
var users = {};
if (y) {
q = q.split(" ");
firstParam = q[0];
secondParam = q[1];
searchQuery = {
is_activated: true,
"privacy.is_profile_public": true,
"privacy.block_list": { $ne: id },
$and: { fname: { "$regex": firstParam, "$options": "i" } }, { lname: { "$regex": secondParam, "$options": "i" } },
}
User.find(searchQuery, function (err, users) {
if (err || !users) {
return reject({
status: 404,
message: "User not found",
});
}
return resolve(users);
},
).sort({ fname: 1 }).collation({ locale: "en", caseLevel: true }).sort({ lname: 1 }).collation({ locale: "en", caseLevel: true });
}
else {
searchQuery1 = {
is_activated: true,
"privacy.is_profile_public": true,
"privacy.block_list": { $ne: id },
fname: { "$regex": q, "$options": "i" },
};
searchQuery2 = {
is_activated: true,
"privacy.is_profile_public": true,
"privacy.block_list": { $ne: id },
lname: { "$regex": q, "$options": "i" },
};
userslist1 = await this.searchCompanion1(searchQuery1);
userslist2 = await this.searchCompanion2(searchQuery2);
users = userslist1 + userslist2
return resolve(users);
}
});
},
searchCompanion1: function (Q) {
return new Promise((resolve, reject) => {
User.find(Q, function (err, users) {
if (err || !users) {
console.log(err);
}
return resolve(users);
},
).sort({ fname: 1 }).collation({ locale: "en", caseLevel: true }).sort({ lname: 1 }).collation({ locale: "en", caseLevel: true });;
});
},
searchCompanion2: function (Q) {
return new Promise((resolve, reject) => {
User.find(Q, function (err, users) {
if (err || !users) {
console.log(err);
}
return resolve(users);
},
).sort({ fname: 1 }).collation({ locale: "en", caseLevel: true }).sort({ lname: 1 }).collation({ locale: "en", caseLevel: true });;
});
},