如何 Mongo 只查询在搜索表单中输入的字段?

How to Mongo query for only fields entered in Search Form?

我有一个用作过滤器的搜索表单。我只想将输入内容的字段用于 Mongo 查询。

这是我的后端 Routes.js。如果用户没有为 seat_price_static 输入任何内容,则此 .find() 不应尝试匹配两个参数上的 $and。

// Routes.js from backend
app.get('/search', function(req, res, next){
   Trip.find({
         $and: [
              {seats_remaining: {$gte: req.query.seats_remaining}},
              {seat_price_static: {$lte: req.query.seat_price_static}}
         ]
   }, function(err, trips){
         if(err){return next(err)};
         return res.json(trips);
   });
});

如何设置这种灵活性?

//========================================= ========================// //================== 如果需要,一些额外的信息 ======================//

这是我的前端搜索字段。如果仅输入 seats_remaining,那么我希望 Mongo 查询忽略 seat_price_static 字段。

// searchForm.html
<input type='number' ng-model='search.seats_remaining'>
<input type='number' ng-model='search.seat_price_static'>
<button ng-click='searchIt(search)'>Search</button>

这是我的客户端 Controller.js。如您所见,它将 search 对象发送到后端。

// Controller.js from front-end client
App.controller('appCtrl', function($scope, $http){
   $scope.searchIt = function(search){
      $http.get('http://localhost:3000/search', {params: search})
          .then(function(data){
              console.log('Got the search results ' + data);
          }, function(err){
              console.log(err);
          });
   }
};

我正在使用 MEAN 堆栈。

您不必为此使用 $and。您在查询文档中提供的任何逗号分隔的键值对都隐式 ANDed

现在对于您的情况,您可以做的是创建一个查询文档。之后,检查 req.query 是否包含 seats_remaining 和 seat_price_static 值。如果是,请将它们添加到查询文档中。

如果不离开他们。像这样:

var query = {};

if(req.query.seats_remaining) query.seats_remaining = {$gte: {req.query.seats_remaining }};

对 req.query seat_price_static 执行相同的操作。

然后:

Trip.find(query, function(err, trips){ //your code to handle the response from MongoDB  })

希望这对您有所帮助。