javascript - 如何在猫鼬中查找文档并从对象数组中返回最近 10 天?
问题描述
我正在尝试findOne
记录并返回此文档数组中最近 10 天的对象。schema
就是这个:
const CurrenciesSchema = new mongoose.Schema({
currency: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
exchange_rate: {
type: Number,
required: true
},
spread: {
type: Number,
required: true,
default: 0,
select: false
},
lastUpdate: {
type: Date
},
createdAt: {
type: Date,
default: Date.now
},
history: [
{
date: Date,
rate: Number
}
]
});
我正在尝试查询特定货币并history
从过去 10 天的数组中返回对象。
我query
的是这个:
async rateHistory(req) {
try {
const date = moment().subtract(10, "days");
return await Currencies.findOne({
currency: req.params.id,
history: {
$elemMatch: {
date: { $gte: date._d }
}
}
});
} catch (e) {
return new Error(e);
}
}
但是,当我运行此代码时,它返回正确的货币但所有history
数组。
我错过了什么?
编辑:我也试过这个:
async rateHistory(req) {
try {
const date = moment().subtract(10, "days");
return await Currencies.aggregate(
{ $match: { currency: req.params.id } },
{ $unwind: "$history" },
{ $match: { "history.date": { $gte: date._d } } }
);
} catch (e) {
return new Error(e);
}
}
但这不会返回任何东西
解决方案
我找到了进行查询的正确方法:
async rateHistory(req) {
try {
const date = moment().subtract(10, "days");
return await Currencies.aggregate([
{
$match: { currency: req.params.id }
}
])
.unwind("history")
.match({ "history.date": { $gte: date._d } });
} catch (e) {
return new Error(e);
}
}
推荐阅读
- javascript - React 网站无法完全加载并出现故障
- python - Django通过ajax发送图像文件但request.FILES为空
- python - Plotly 给出的值错误不断发生
- jquery - 使用 foreach 进行多个 Ajax 调用
- c++ - 在 C++ 中获得二维数组中前 3 名的平均值
- vue.js - 如何将图像位置传递给 Vue 中的子组件?
- c# - 调用 LoadLibrary 然后调用 FreeLibrary 会中断网络
- angular - 如何让值提供者以角度读取更新的值
- java - 对等方重置连接:套接字写入错误 - 使用 java 套接字
- typescript - tsc 没有正确检查类型相等性/可分配性