简体   繁体   English

如何用mongoose绑定mongodb中的搜索值

[英]How bind search values in mongodb with mongoose

I have the following code in my /search/:query route: 我的/ search /:query路由中有以下代码:

var param = {
    query: req.query['query']
}

MyModel.find({
        "$or": [
            { 'name': req.param.query },
            { 'age': req.param.query  },
            { 'event': req.param.query },
        ]
    }, function (err, results) {
        if (err) {
            console.log(err)
        }
        else {
            res.render('index', { 
                data: results
            });
        }
    }
);

And is good, i can search for pretty much every data that i want, but only individually. 很好,我可以搜索几乎所有我想要的数据,但只能单独搜索。 What if i want search name + age, can i? 如果我想输入搜索名称+年龄怎么办? Example: 'Leo 22'. 例如:“狮子座22”。

There is any way that mongoose help me with this? 猫鼬有什么办法可以帮助我呢?

UPDATE: 更新:

My problem is: 我的问题是:

I have tables lists it titles, this title is the concatenation of 'eventName' and 'eventDate'. 我有表格列出了标题,该标题是“ eventName”和“ eventDate”的串联。

Real examples of this fields: 该字段的真实示例:

'Special Event - 20/12/2015' 'Classic Event - 12/03/2015' 'Hot Summer Event - 05/07/2005' '特别活动-2015年12月20日''经典活动-2015年12月3日''夏季热活动-2005年5月7日'

Every week will be create 4 events. 每周将创建4个事件。 In some point, a user will search for an old event, and i believe that the user will search in this format:'EVENT NAME - EVENT DATE'.. 在某个时候,用户将搜索旧事件,我相信用户将以以下格式搜索:“事件名称-事件日期”。

So i need a way to bind this values in my controllers. 因此,我需要一种在控制器中绑定此值的方法。

I'm no familiar with mongoose but in order to do that, you must have a way to bind your query param to the attribute you want to search. 我不熟悉mongoose但是要做到这一点,您必须有一种将查询参数绑定到要搜索的属性的方法。 Otherwise, they wouldn't know Leo is name and 22 is age. 否则,他们不会知道Leo是名字,而22是年龄。

Ur path would be like search?name=:name&age=:age&event=:event and in your code, you will have to process like if the param is not null , add and condition to it. 您的路径就像search?name=:name&age=:age&event=:event ,在您的代码中,您必须像处理param不为null一样对其进行处理和添加条件。

It seems you are using only one parameter ( req.param.query ) to filter all attributes. 似乎您仅使用一个参数( req.param.query )来过滤所有属性。 That's not mongoose related: you could create distinct parameters for each attribute and pass them along the query string. 这与猫鼬无关:您可以为每个属性创建不同的参数,并将其沿查询字符串传递。

For instance: 例如:

"$or": [
        { 'name': req.param.name },
        { 'age': req.param.age  },
        { 'event': req.param.event },
    ]

And your HTTP request will be like this: 您的HTTP请求将如下所示:

http://youraddress/expressRoute?name=Leo&age=22 HTTP:// youraddress / expressRoute名称=利奥&年龄= 22

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

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