javascript - Nodejs 如何在 Controller 中动态操作 MongoDB 聚合?

标签 javascript node.js mongodb mongoose

我的 Nodejs Controller 中有一个非常漫长的聚合:

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”:

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 是否会按照您想要的方式工作,但您可以尝试一下。

关于javascript - Nodejs 如何在 Controller 中动态操作 MongoDB 聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43995097/

相关文章:

javascript - 为什么我的 Anytime DateTimePicker jQuery 插件仍然是一个通用文本框?

node.js - 初始化后更改梦Night的可见性

javascript - Sequelize 删除钩子(Hook)?

node.js - 参数错误,node.js 中的 options.body?

node.js - 将集合中文档的属性减去不同集合中另一个文档的属性,并返回差值数组

mongodb - 大小大于 MaxDocumentSize

javascript - Jquery 菜单 ul 切换

javascript - JSON 解析错误 : Unexpected identifier "Try"

node.js - mongodb Node 驱动程序 connect() 忽略 connectTimeoutMS (和 socketTimeoutMS)设置

javascript - 嵌套 ng-repeat 中的复选框不可单击