私はnodejsコントローラでは非常にloooong集計があります。nodejsコントローラ内のMongoDB集約を動的に操作する方法は?
agentSaleModel.aggregate([
{
$match: {
$and:
[{
_id: { $in: req.body.propertyID },
active : true
}]
}
}, etc....
を私は[「property01」、「property02」]などのような私req.body.propertyID の要素を得たとき、それは素晴らしい作品...
私の問題は、req.body.propertyIDに何もないときにも集約が機能したいということです。 (空白のとき) - すべてのレコードを取得します。
これは動作しません:
agentSaleModel.aggregate([
{
$match: {
$and:
[{
_id: { $in: '' },
active : true
}]
}
}, etc....
そうではなく、ほぼ同じコードの2つの巨大なセットで「あれば」やって:
if (req.body.propertyID) {
...the entire aggregate...
} else {
...the entire aggregate minus the _id: { $in: req.body.propertyID },...
}
これを行うには、よりスマートな方法はありますか?
解決策!
if(!req.body.properyID){
req.body.propertyID = [ ".*" ];
}
agentSaleModel.aggregate([
{
$match: {
$and:
[{
_id: { $in: req.body.propertyID },
active : true
}]
}
}, etc....
しかし、これは遅いかもしれません:のようにあなたも、正規表現を使用することができ
let query = [
{
$match: {
$and:
[{
active : true
}]
}
}];
if(req.body.propertyID) {
query[0]["$match"]["$and"][0]["_id"] = { $in: req.body.propertyID };
}
agentSaleModel.aggregate(query, ...)
: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)
はい!!!あなたの提案は実際に働いた! - 私はあなたがそれを見ることができるように質問に私の最終的な解決策を掲載させてください。どうもありがとうございます。私は本当にあなたがオブジェクトを構築し、大きな集合体に注入することができないことを本当に理解していません:) – torbenrudgaard