i am trying to reproduce the "like" behavior in mongoose by searching all elements where user name is something like "abcd..." this function return abject that i feed db.find function with
const rgx = (pattern) => new RegExp(`.*${pattern}.*`);
const orFilter = [];
fields.forEach((field) => {
if (field.includes('.')) {
const [parent, child] = field.split('.');
orFilter.push({
[parent]: { [child]: { $regex: rgx(searchText), $options: 'i' } },
});
} else {
orFilter.push({ [field]: { $regex: rgx(searchText), $options: 'i' } });
}
});
return { $or: orFilter };
entry 1: ['city','zipCode'] working ok
entry 2 : ['city','zipCode','user.name'] does not work.
i have this message *CastError: Cast to ObjectId failed for value { name: { '$regex': /.abc./, '$options': 'i' } } *