首页 > 解决方案 > 如何在猫鼬中查找文档并从对象数组中返回最近 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);
        }
    }

但这不会返回任何东西

标签: javascriptnode.jsmongoose

解决方案


我找到了进行查询的正确方法:

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

推荐阅读