Rey
Rey

Reputation: 1433

Converting Mongo ID to String to do Comparison

I have a search feature that returns filtered data from my mongoDB based on a user's input for various filters. So, for instance I can do this and it works:

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 returns a filtered data set where the results match whatever was passed in by the user in a comma separated list.

However, I am running into a challenge in comparing a user inputed value with an _id value in our mongo db. Of course, the _id I'm checking against here is not a string, but a mongo objectId -- that's the issue as far as I can tell. So I'm trying to figure out how I can convert either the input, or the _id, or both, to do a valid comparison. This was the initial code:

if (person) search['_id'] = person;

That doesn't work, because the value for person here is a string, and _id is not -- as I said, _id is a mongo objectId. So how can I do a type conversion to handle this check?

I tried this but it causes errors:

if (person) search['_id'].toString() = person;

What would the syntax look like for this kind of comparison?

Upvotes: 0

Views: 168

Answers (1)

Sébastien
Sébastien

Reputation: 12139

In mongoDB you can use ObjectId.valueOf()

From the documentation

ObjectId("507c7f79bcf86cd7994f6c0e").valueOf()

will return the following string:

507c7f79bcf86cd7994f6c0e

Upvotes: 2

Related Questions