node.js - 查询 mongoose 中的填充字段
问题描述
如何在我的猫鼬查询中设置此条件?
请注意,coinId 是一个填充字段
signalModel
.find(
{
'coinId.Price': { $gt: 1000 }
},
(err, signals) => {
if (err) throw err
res.json(signals)
}
)
.populate('coinId')
更新:
我从答案中尝试了这个查询,但我对结果不满意,因为 coin 字段是一个空数组。
let signals = await signalModel.aggregate([
{
$lookup: {
from: 'Coin',
localField: 'coinId',
foreignField: '_id',
as: 'coin'
}
},
{
$match: {
type: req.query.type ?? /^(buy|sell)$/i,
'coin.Price': { $gt: 1000 }
}
}
])
结果:
{
"_id": "616eb8d2c31a52512900f56b",
"coinId": "616e8c07ca518ef7fac3eea9",
"type": "buy",
"highEntryPoint": 60000,
"lowEntryPoint": 59500,
"stopLoss": 59000,
"takeProfit": 60500,
"lastPrice": 61998.1102423889,
"status": "waiting",
"__v": 0,
"coin": []
}
更新2
输入示例/信号
{
"_id" : ObjectId("616eb8d2c31a52512900f56b"),
"coinId" : ObjectId("616e8c07ca518ef7fac3eea9"),
"type" : "buy",
"highEntryPoint" : 60000,
"lowEntryPoint" : 59500,
"stopLoss" : 59000,
"takeProfit" : 60500,
"lastPrice" : 61998.1102423889,
"status" : "waiting",
"__v" : 0
}
输入示例/硬币
{
"_id" : ObjectId("616e8c07ca518ef7fac3eea9"),
"Name" : "BTC",
"Price" : 61700.9584311177,
"__v" : 0
}
解决方案
首先使用$lookup
然后添加条件,如下所示:
signalModel.aggregate([
{$lookup:{
from: 'Coins' // coins collection name
localField: coindId,
foreignField: _id
as: coins
}},
{
$match:{'coins':{$ne: []}}
}
,{
$match :{"coins.Price":{$gt:1000}}
}
])
推荐阅读
- git - git submodule update 排除子模块列表
- gitlab-ci - 当 gitlab 运行程序作业失败并退出代码 137 时,我可以设置通知吗?
- docker - Docker 容器上的 Mirosoft 办公室
- vb.net - 如何使用不同类中的共享函数登录到 RichTextBox
- python - 两个列表的对应元素相同的索引列表
- node.js - Node.js puppeteer 错误 DeprecationWarning 和 UnhandledPromiseRejectionWarning
- wordpress - 大型交互式表格的 Wordpress 插件
- javascript - 将对象转换为数组,并将其乘以对象值
- javascript - 控制流。回调、承诺、异步/等待背后的逻辑。有点什么意思?
- javascript - JS 类实例的 VSCode Intellisense 不起作用