Home > Software design >  Query nested object mongoose
Query nested object mongoose

Time:09-18

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' } } *

CodePudding user response:

Try to filter all fields in the same manner adding single quotes to the field name:

const orFilter = [];
fields.forEach((field) => {
  orFilter.push({ [`'${field}'`]: { $regex: rgx(searchText), $options: 'i' } });
});
return { $or: orFilter };

A { 'user.name' : { $regex: ... } } filter should work.

CodePudding user response:

the solution to my probleme was found by using aggregation visit https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate/! i tried to access a value stored in another table user.name

  • Related