Specifying Mongo Query Parameters From Client Controller (MEAN.JS)

微笑、不失礼 提交于 2019-12-03 07:30:55

It's probably not the cleanest way, but you can create a new service (or edit the current one to work with several parameters):

.factory('ArticlesService2', ['$resource',
    function($resource) {
        return $resource('articles/:param1/:param2', {
            param1: '',
            param2: ''
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

Then call it in your controller :

$scope.findWithParams = function() {
    $scope.article = ArticlesService2.query({
        param1: $scope.aYearFromNow,
        param2: $scope.aMonthAgo
    });
};

On the back-end, you'll need to prepare a route :

app.route('/articles/:param1/:param2')
    .get(articles.listWithParams)

Add a function to your back-end controller :

exports.listWithParams = function(req, res) {
    Article.find()
    .where('date')
    .lt(req.params.param1)
    .gt(req.params.param2)
    .sort('-created').populate('user', 'displayName')
    .exec(function(err, articles) {
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        } else {
            res.jsonp(articles);
        }
    });
};

Should work, haven't tested it though.

Another way is to just pass the search parameters in the query method, like this:

 $scope.searchart = function() {
    Articles.query({start:$scope.startDate, end:$scope.endDate}, function(articles) {
        $scope.articles = articles;
    });
};

and then at the server side controller, read your query string parameters like this:

exports.searcharticle = function(req, res) {
    Article.find().where('date').gt(req.query['start']).lt(req.query['end']).exec(function(err, articles) {
        if (err) {
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(articles);
        }
    });
};

This way doesn't require more routes or services.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!