猫鼬搜索查询

时间:2016-10-25 23:58:01

标签: javascript node.js mongodb mongoose

我正在使用Mongoose通过Mongodb数据库实现搜索。在客户端,我有:

var searchQuery = {
            title: ($('#responseTitle').val()),
            text: ($('#responseKeywords').val())
        };

$.ajax({
        type: "GET",
        url: "../../api/threads",
        data: searchQuery,
        success: function(data){
            prefetchedResponses = data;
            loadResponseBrowser();
        }
    })

在服务器端,我有:

router.get('/', function(req, res, next) {
    Response.find(req.query, function(err, foundResponses){
    ...

这样可行,但只返回与确切字段匹配的内容。我想实现一个正则表达式搜索。但是,我无法决定是在客户端还是在服务器端执行此操作。在服务器端,它将涉及遍历req.query的每个字段并附加必要的属性以启用正则表达式搜索。在客户端,只需使用预定义的属性构建titletext,就会更容易。但是,在客户端进行此操作似乎对我不利,因为后端可能随时发生变化。

Mongoose中是否有第三种选择允许我将regex应用于所有字段?

3 个答案:

答案 0 :(得分:0)

您可以将正则表达式传递给mongoose。这很容易做到以下几点:

router.get('/', function(req, res, next) {

    var regexQuery = {
      title: new RegExp(req.query.title, 'i')
      text: new RegExp(req.query.text, 'i')
    }
    Response.find(regexQuery, function(err, foundResponses){
    ...

答案 1 :(得分:0)

没有第三种选择,你必须在客户端定义你的正则表达式:

CC

或在服务器端

CC

答案 2 :(得分:0)

使用POST方法代替GET方法。

客户端javascript

var searchQuery = {
    title: ($('#responseTitle').val()),
    text: ($('#responseKeywords').val())
};

$.ajax({
    type: "POST",
    url: "../../api/threads",
    data: searchQuery,
    success: function(data) {
        prefetchedResponses = data;
        loadResponseBrowser();
    }
})

服务器端javaScript

router.post('/threads', function(req, res, next) {
    var searchTitle = req.body.title;
    var searchText = req.body.text;
    var regexValue1 = '^' + searchTitle;
    var regexValue2 = '^' + searchText;
    var queryOptions = {
        $and: [{
            searchTitle: {
                '$regex': regexValue1,
                '$options': 'i'
            }
        }, {
            text: {
                '$regex': regexValue2,
                '$options': 'i'
            }
        }]
    }
    var promise = Response.find(queryOptions);
    promise.then(function(data) {
        if (data) {
            return res.status(200).json(data);
        } else {
            return res.status(422).json('No data')
        }
    });
    promise.catch(function(error) {
        return res.status(500).json(error);
    });
});