簡體   English   中英

Node.js如何在控制器中動態操縱MongoDB聚合?

[英]nodejs how to dynamically manipulate your MongoDB aggregate in your controller?

我的nodejs控制器中有一個非常寬松的集合:

agentSaleModel.aggregate([
    {
        $match: {
            $and: 
            [{ 
                _id: { $in: req.body.propertyID },
                active : true
            }]
        }
    }, etc....

當我在req.body.propertyID中獲得諸如[“ property01”,“ property02”]等元素時,它的效果很好。

我的問題是,當req.body.propertyID中沒有任何內容時,我也希望聚合工作。 (空白時)-然后獲取所有記錄。

這不起作用:

agentSaleModel.aggregate([
    {
        $match: {
            $and: 
            [{ 
                _id: { $in: '' },
                active : true
            }]
        }
    }, etc....

因此,與其對兩組幾乎完全相同的代碼進行“如果”分析:

if (req.body.propertyID) {
   ...the entire aggregate... 
} else {
   ...the entire aggregate minus the _id: { $in: req.body.propertyID },... 
}

有更聰明的方法嗎?

解!! 感謝FluffyNights :)

if (req.body.propertyID!='') {
    var matchStr = { 
        $match: {
            $and: 
            [{ 
                _id: { $in: req.body.propertyID },
                active : true
            }]
        }
    }
} else {
    var matchStr = { 
        $match: {
                active : true
        }
    }
}
agentSaleModel.aggregate([ matchStr, etc..... (rest of pipeline)

您可以這樣做:

let query = [
    {
        $match: {
            $and: 
            [{ 
                active : true
            }]
        }
    }];
if(req.body.propertyID) {
   query[0]["$match"]["$and"][0]["_id"] = { $in: req.body.propertyID };
}
agentSaleModel.aggregate(query, ...)

您還可以使用正則表達式,例如:

if(!req.body.properyID){
    req.body.propertyID = [ ".*" ];
}
agentSaleModel.aggregate([
{
    $match: {
        $and: 
        [{ 
            _id: { $in: req.body.propertyID },
            active : true
        }]
    }
}, etc....

但是,這可能會變慢。 我不確定是否將null傳遞給$ in是否可以按照您想要的方式工作,但是您可以嘗試一下。

嘗試在運行查詢之前構造查詢呢?

例如。

var query = req.body.propertyID ? { $and: [{_id: { $in: req.body.propertyID }, active : true}]} : {active : true}

agentSaleModel.aggregate([
{
   $match: query
}, etc....

希望這可以幫助。

這是使用計算出的屬性名稱的內聯解決方案:

$match: {
  $and: [
    {
      _id: { [ req.body.propertyID ? '$in' : '$exists' ] : req.body.propertyID || true },
      active: true,
    },
  ],
}

當存在req.body.propertyID時,查詢變為:

_id : { $in : req.body.propertyID }

如果不:

_id : { $exists : true }

編輯 :如果您明確想匹配所有文檔,這還將允許req.body.propertyID等於"ALL"

let selectAll = ! req.body.propertyID || req.body.propertyID === 'ALL';
const query = {
  $match: {
    $and: [
      {
        _id: { [ selectAll ? '$exists' : '$in' ] : selectAll || req.body.propertyID },
        active: true,
      },
    ],
  },
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM