1

I have a search feature where filtered data is returned from my mongoDB based on a user's input for various filters. Here's an example, where records are returned that match for lastName values. This array of values is passed in to Mongoose/Mongo using $in:

if (lastName) {
    let arrlastName = [];
    arrlastName = lastName.split(",");
    _.each(arrlastName, (l, key, c) => {
        arrlastName[key] = new RegExp(arrlastName[key], "i");
    });
    search['name.last'] = { $in: arrlastName };
}

The above code works as expected.

However, in addition to matching for names, I want to return records based on a filter that evaluates a user's "_id". The challenge is, "_id" here is not a string, but a mongoDB object Id.

Now, this is easy enough to do when I'm searching for a single value for "_id", in which case I would just do this:

  if (personId) search['_id'] = new mongo.ObjectID(personId);

That also works as expected. This will return just the results that match this one _id.

But how do I evaluate against an array of values in this situation - like I'm doing for lastName in the code near the top of this question? What would that look like? This is what I tried (that did not work):

  if (person) {
    let personId = new mongo.ObjectID(person);
    let arrPerson = [];
    arrPerson = personId.split(",");
    _.each(arrPerson, (l, key, c) => {
    arrPerson[key] = new RegExp(arrPerson[key], "i");
    });
    search['_id'] = { $in: arrPerson };
  }
Rey
  • 1,393
  • 1
  • 15
  • 24

1 Answers1

2

Your tag & the intro to your question mention mongoose, but all of your logic seems to be using mongo directly.

If you are using mongoose this answer should solve your question.

Otherwise, this logic from the MongoDB documentation may be helpful

db.bios.find(
  {
    _id: { $in: [ 5,  ObjectId("507c35dd8fada716c89d0013") ] }
  }
)
Austin
  • 114
  • 7