我的 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/