繁体   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