mongodb - 基于mongoose js中字段的条件查询获取文档
问题描述
我有这样的模型
const schema = new mongoose.Schema({
locationtype: String, // one of "all","locationstoshow","locationsnottoshow"
locations: [{
location_country: String,
location_state: String,
location_city: String
}]
});
export default mongoose.model("AdPost", schema);
现在我有了当前用户的国家、州和城市的值。我想获得那些满足这些条件的广告文件-
如果 locationtype 为“all”,则应返回所有文档,
如果 locationtype 为“locationstoshow”,则应检查每个文档是否允许当前用户的国家、州和城市。如果是,它们应该被退回。否则不是。
如果 locationtype 是“locationsnottoshow”,那么每个文档都应该检查用户的位置是否不包含在位置中并返回它。否则不是。
请注意,如果未提及城市(即 location_city: "")并且位置中提及了州和国家,则检查用户的国家和州,如果仅提及国家,则城市和州为“”。然后,匹配用户的国家。
我在想这样的事情,但它没有给出正确的结果。
let query = [{
"$cond": {
"if": {
"$eq": [ "locationtype", "all" ]
},
"then": {
"$match": [{
"$cond": {
"if": {
"$neq": [ "locations.location_city", "" ]
},
"then": {
"$neq": [ "locations.location_city", "" ]
},
"else": {
"if": {
"$neq": [ "locations.location_state", "" ]
},
"then": {
"$eq": [ "locations.location_state", "" ]
},
"else": {
"$eq": [ "locations.location_country", "" ]
}
}
}
}]
},
"else": {
"if": {
"$eq": [ "locationtype", "locationstoshow" ]
},
"then": {
"$match": [{
"$cond": {
"if": {
"$neq": [ "locations.location_city", "" ]
},
"then": {
"$eq": [ "locations.location_city", `${city}` ]
},
"else": {
"if": {
"$neq": [ "locations.location_state", "" ]
},
"then": {
"$eq": [ "locations.location_state", `${state}` ]
},
"else": {
"$eq": [ "locations.location_country", `${country}` ]
}
}
}
}]
},
"else": {
"if": {
"$eq": [ "locationtype", "locationsnottoshow" ]
},
"then": {
"$match": [{
"$cond": {
"if": {
"$neq": [ "locations.location_city", "" ]
},
"then": {
"$neq": [ "locations.location_city", `${city}` ]
},
"else": {
"if": {
"$neq": [ "locations.location_state", "" ]
},
"then": {
"$neq": [ "locations.location_state", `${state}` ]
},
"else": {
"$neq": [ "locations.location_country", `${country}` ]
}
}
}
}]
},
}
}
}
}];
const options = {
limit: 10,
page: pageNo
}
AdPost.aggregatePaginate(query, options).then(docs => {
res.json({ docs });
}).catch(err => {
res.status(400).json({ errors: err });
})
解决方案
推荐阅读
- mysql - Python tempfile NamedTemporaryFile 文件在尝试访问它以进行读取时未找到
- javascript - 等效于 Vanilla JS 中的 Jquery $(document).ajaxsend()
- perl - 无法将合并数据写入 yml 文件
- angular-material - 角材料隐藏禁用选择选项
- python - 如何将 json 转储中的多个数据帧解压缩到 Pandas 数据帧中
- php - 如何将我的主机站点介绍给madeline proto电报
- javascript - 如何为原生按钮添加线性渐变背景?
- excel - VBA:将命名范围粘贴到命名单元格
- python - 创建一个循环,输出每个人的年龄和姓名。格式为“姓名(有年龄)”
- visual-studio-code - VScode:如何从 npm 脚本搜索中排除某些文件夹