如何使用猫鼬在URL参数中包括%20的字符串搜索

时间:2019-09-30 05:34:37

标签: mongodb express mongoose

我对MEAN堆栈开发有些陌生,并且在我的项目中使用了https://github.com/diegohaz/rest。我正在尝试通过slug筛选我的猫鼬查询,但是如果字符串上包含%20,它不会显示结果。我的数据库中的示例。

{name:"fname lname", slug:"fname%20lname"}

然后,如果我这样搜索它,将没有结果。

domain.com/by_slug/fname%20lname

但是,如果我尝试这样删除数据库中的%20

{name:"fname lname", slug:"fname lname"}

则结果正确。我认为%20已删除,并在搜索过程中转换为空间。抱歉,我来自PHP,MySQL环境。

这是我的控制器代码。

    export const showBySlug = ({ params, query }, res, next) =>   
    Staff.find({ 'slug': params.slug })
    .then(notFound(res))
    .then((staff) => staff.map((staff) => staff.view()))
    .then(success(res))
    .catch(next)

1 个答案:

答案 0 :(得分:0)

感谢尼尔·伦恩的回答。

使用

似乎有问题
params.slug.replace(/ /,"%20")

因为如果子段为3个字,则会引发一些错误。因此,我不使用replace而是使用encodeURIComponent()将其编码回来,因为它是由express自动解码的。

Staff.findOne({ 'slug': encodeURIComponent(params.slug) })
    .then(notFound(res))
    .then((staff) => staff ? staff.view() : null)
    .then(success(res))
    .catch(next)