【发布时间】:2022-01-20 23:37:48
【问题描述】:
我的 nodejs 代码中有 MongoDB 的聚合查询。
const query = {
'$expr':{
'$and':[
{'$eq': ['$appId', req.user.appId]},
]
}
}
从前端收到一个过滤器对象,如下:
{
shops: '604c776763c302032e610347',
offset: '0',
limit: '20',
}
我需要在查询中动态推送商店 ID。需要是 appId -> user.appID AND targetFrom || targetTo 来自过滤器对象)
shops 可以是一个 id 或 id 数组,为此我使用$in 运算符
query['$expr']['$and'].push({
$eq: [
{
$or: [
{"targetFrom": {$in: bb}},
{"targetTo": {$in: bb}}
]
}
]
})
旧版代码如下:
const query = {
$and: [
{appId: req.user.appId}
]
}
query['$and'].push({
$or: [
{"targetFrom": {$in: bb}}, <- in bb is mongodb objectID
{"targetTo": {$in: bb}}
]
})
更新
如何在我的 items 对象数组中按 ID 搜索一些 item?
if(req.query.products) {
typeof req.query.products === 'string' ? req.query.products = [req.query.products] : req.query.products
let bb = req.query.products.map(function(el) { return mongoose.Types.ObjectId(el) })
query['$expr']['$and'].push({
$and: [
{
items: {
$in: ['item.itemId', bb]
}
}
]
})
}
【问题讨论】:
标签: node.js typescript mongodb express mongoose