[英]How to find a document in mongoose and return the last 10 days from array of objects?
I'm trying to findOne
document and return the last 10 days of objects in this document array.我正在尝试
findOne
文档并返回此文档数组中最近 10 天的对象。 The schema
is this one: 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
}
]
});
I'm trying to query a specific currency and return the objects from the history
array from the last 10 days.我正在尝试查询特定货币并从过去 10 天的
history
数组中返回对象。
My query
is this one:我的
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);
}
}
However, when I run this code, it returns the correct currency but all history
array.但是,当我运行此代码时,它返回正确的货币但所有
history
数组。
What am I missing?我错过了什么?
Edit: I also tried this:编辑:我也试过这个:
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);
}
}
But this doesn't return anything但这不会返回任何东西
I found the right way to make the query:我找到了进行查询的正确方法:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.