Home > Back-end >  Mongoose find field with any value
Mongoose find field with any value

Time:06-07

I have a find query like:

 person = await PersonSchema.find({
        givenName: (gn == 'none') ? {} : gn,
        lastName: (ln == 'none') ? {} : ln,
        placeOfBirth: (pob == 'none') ? {} : pob,
        dob: { $regex: (dob == 'none') ? {} : dob }
    });

basically, if any of these fields equal 'none' I want to get all value returned... basically removing it from the query... does anyone know how to do this?

Or even think of another way of approaching this problem?

CodePudding user response:

You should use $and in case your two fields don't equal 'none'. Maybe Like this ;

const filter = [{}] // if all field equal none, default $and
gn !== 'none' && filter.push({givenName: gn})
ln !== 'none' && filter.push({lastName: ln})
pob !== 'none' && filter.push({placeOfBirth: pob})
dob !== 'none' && filter.push({dob: dob})

person = await PersonSchema.find({$and : filter});

  • Related