首页 > 解决方案 > 如何对来自 Alpha Vantage API 的金融系列数据应用阈值和分页?

问题描述

我正在使用 Alpha Vantage API 来获取金融市场数据并将其存储在 mongo 中。我的mongo方案是这样的:

import * as mongoose from 'mongoose'

export interface Symbol extends mongoose.Document {
    code: string,
    data_frame: object[],
    createdAt: Date,
    updatedAt: Date
}

const symbolSchema = new mongoose.Schema({
    code:{
        type: String,
        required: true,
        unique: true
    },
    data_frame:{
        type: [Object],
        default: {}
    },
    createdAt:{
        type: Date,
        default: Date.now()
    },
    updatedAt:{
        type: Date
    }
}, {timestamps: true})

export const Symbol = mongoose.model<Symbol>('Symbol', symbolSchema)

这是 Alpha Vantage API 呈现数据的方式:

[
    {
        "2021-07-02": {
            "1. open": "17.39",
            "2. high": "17.63",
            "3. low": "17.25",
            "4. close": "17.43",
            "5. adjusted close": "17.43",
            "6. volume": "24228000",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        },
        "2021-07-01": {
            "1. open": "16.86",
            "2. high": "17.32",
            "3. low": "16.82",
            "4. close": "17.2",
            "5. adjusted close": "17.2",
            "6. volume": "39101898",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
        },
        "2021-06-30": {
            "1. open": "17.15",
            "2. high": "17.46",
            "3. low": "17.02",
            "4. close": "17.07",
            "5. adjusted close": "17.07",
            "6. volume": "28807699",
            "7. dividend amount": "0.0000",
            "8. split coefficient": "1.0"
...

]

我将历史数据存储为一个对象,就像它来自 Alpha Vantage API 一样。我在跳过和限制来自我自己的 API 的查询时遇到问题。换句话说,我想只接收x历史数据并能够应用分页,但我不能。

之前,我使用 Python,并将 Alpha Vantage 历史数据保存为一个数字数组。我使用了以下代码片段并且能够应用文档限制。有人可以帮助我吗?

model.findOne({"code": req.query.code}, {data_frame: {$slice:-req.query.limit}})
                    .then(obj=>res.json(200, obj.data_frame))
                    .catch(next)

我尝试了以下命令但没有成功:

model.aggregate([
                    { $match: { "code": req.query.code } },
                    { $unwind: "$data_frame" },
                    { $limit: 2 }
                ])
                    .then(obj=>res.json(200, obj))
                    .catch(next)

和这个..

model.find({"code": req.query.code})
                    .slice('data_frame', 2)
                    .then(obj=>res.json(200, obj))
                    .catch(next)

标签: node.jsmongodbmongoosealpha-vantage

解决方案


基本上,您必须在每次返回和下一步时更新页面。

let page = 0
let itemsPerPage = 2

    model.aggregate([
                        { $match: { "code": req.query.code } },
                        { $unwind: "$data_frame" },
                        { $limit: itemsPerPage },
                        { $skip:itemsPerPage*page}
                    ])
                        .then(obj=>res.json(200, obj))
                        .catch(next)

推荐阅读