【发布时间】:2020-07-22 13:05:31
【问题描述】:
我的 nodejs api 中有以下 mongo 聚合查询。它工作得很好。
queryRes = await Seller.aggregate([
{$match: {}},{$addFields : {"communication_information":{$filter:{ input: "$communication_information",as: "communication_information",
cond: {"$or" :[{$eq: ["$$communication_information.communication_information_type", "phone" ] },
{$eq: ["$$communication_information.communication_information_type", "email"] },
]}}}}},{ "$project": {"_id": 1,"initial_name": 1,"first_name": 1,"last_name": 1,"gender":1,"communication_information":1, }},
{ $sort : { first_name : 1, last_name: 1 } },])
我想要实现的是,希望将此查询存储在某个属性文件或数据库本身中,并根据某些逻辑获取查询字符串并执行它。 在 Java 中,我能够做到这一点。我可以将所有应用程序查询存储在属性文件中,以便在查询需要更新时避免编译整个应用程序。
可以在 NodeJs 中实现类似的功能。我正在使用 Mongoose 连接 MongoDB? 到目前为止,我能够实现的是,我能够将上述查询存储在 MongoDB 中并获取变量中的字符串。
queryGetter = await Queries.find()
const queryString = queryGetter.qstring // storing query string
queryRes = await Seller.aggregate(queryString)
但这会报错
"Error: Arguments must be aggregate pipeline operators"
提前感谢任何线索来实现这一点
【问题讨论】:
-
如果您将json字符串存储在db中并检索,那么您需要解析字符串
JSON.parse(queryString)。 -
JSON.parse(queryString) 给出了更多错误,它不接受 $match:{}