简体   繁体   English

将Mongo ID转换为字符串以进行比较

[英]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. 我有一个搜索功能,可以根据用户对各种过滤器的输入,从mongoDB返回过滤后的数据。 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. 但是,在mongo数据库中比较用户输入的值和_id值时,我遇到了挑战。 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. 当然,我要检查的_id不是字符串,而是mongo objectId,据我所知这就是问题。 So I'm trying to figure out how I can convert either the input, or the _id , or both, to do a valid comparison. 因此,我试图弄清楚如何转换输入或_id或两者都进行有效的比较。 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. 那是行不通的,因为这里person的值是一个字符串,而_id不是-正如我所说的那样_id是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? 这种比较的语法是什么样的?

In mongoDB you can use ObjectId.valueOf() 在mongoDB中,您可以使用ObjectId.valueOf()

From the documentation 从文档中

ObjectId("507c7f79bcf86cd7994f6c0e").valueOf()

will return the following string: 将返回以下字符串:

507c7f79bcf86cd7994f6c0e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM