I'm trying to findOne
document and return the last 10 days of objects in this document array. The schema
is this one:
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.
My query
is this one:
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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.