簡體   English   中英

如何在貓鼬中查找文檔並從對象數組中返回過去 10 天?

[英]How to find a document in mongoose and return the last 10 days from array of objects?

我正在嘗試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
        }
    ]
});

我正在嘗試查詢特定貨幣並從過去 10 天的history數組中返回對象。

我的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);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM