[英]How to save an array of Web Api data to a child - parent schema in a nested mongoose schema?
我正在嘗試保存Web Api的結果,其中包含多個數據數組以填充股票圖表。 每次輸入符號並單擊“獲取報價”按鈕,它都應從Web api獲取數據,並將其保存在數據庫的“子模式”下。 我該如何使用nodejs和mongoose? 這是我嘗試過的代碼。
文件夾-模型-Stock.js
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
const slug = require('slug')
const childSchemaData = new mongoose.Schema({
date: mongoose.Decimal128,
open: mongoose.Decimal128,
high: mongoose.Decimal128,
low: mongoose.Decimal128,
close: mongoose.Decimal128,
volume: mongoose.Decimal128
})
const parentSchemaSymbol = new mongoose.Schema({
symbol: {
type: String,
trim: true,
minlength: 2,
maxlength: 4,
required: 'Plese enter a valid symbol, min 2 characters and max 4'
},
// Array of subdocuments
data: [childSchemaData],
slug: String
});
//we have to PRE-save slug before save the parentSchemaSymbol into DB
parentSchemaSymbol.pre('save', function (next) {
if (!this.isModified('symbol')) {
next()//skip it
return//stop this function from running
}
this.slug = slug(this.symbol)
next()
//TODO make more resiliant soslug are unique
})
module.exports = mongoose.model('Stock', parentSchemaSymbol)
控制器-webApiController.js
const mongoose = require('mongoose')
const axios = require('axios')
require('../models/Stock')
const parentSchemaSymbol = mongoose.model('Stock')
mongoose.Promise = global.Promise // Tell Mongoose to use ES6 promises
// Connect to our Database and handle any bad connections
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true })
mongoose.connection.on('error', (err) => {
console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`)
})
exports.webApi = (req, res) => {
let curValue = req.params.symbol
axios.get(`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${curValue}&outputsize=compact&apikey=TUVR`)
.then(response => {
return highLow = Object.keys(response.data['Time Series (Daily)']).map(date => {
return [
Date.parse(date),
Math.round(parseFloat(response.data['Time Series (Daily)'][date]['1. open']) * 100) / 100,
Math.round(parseFloat(response.data['Time Series (Daily)'][date]['2. high']) * 100) / 100,
Math.round(parseFloat(response.data['Time Series (Daily)'][date]['3. low']) * 100) / 100,
Math.round(parseFloat(response.data['Time Series (Daily)'][date]['4. close']) * 100) / 100,
parseInt(response.data['Time Series (Daily)'][date]['5. volume'])
]
})
})
.then(_ => {
let curValueSchema = new parentSchemaSymbol()
curValueSchema.symbol = curValue;
curValueSchema.data.push(highLow);
curValueSchema.slug = 'String';
curValueSchema.save().then(doc => {
console.log('Saved the symbol', doc)
res.send(highLow)
}).catch(e => {
console.log(e)
})
})
.catch(error => {
console.log(error);
})
}
Web API結果= highLow
請查看您的axios請求調用,並將其更改為此
axios.get(`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${curValue}&outputsize=compact&apikey=TUVR`)
.then(response => {
return highLow = Object.keys(response.data['Time Series (Daily)']).map(date => {
return {
data :Date.parse(date),
open : Math.round(parseFloat(response.data['Time Series (Daily)'][date]['1. open']) * 100) / 100,
high :Math.round(parseFloat(response.data['Time Series (Daily)'][date]['2. high']) * 100) / 100,
low : Math.round(parseFloat(response.data['Time Series (Daily)'][date]['3. low']) * 100) / 100,
close : Math.round(parseFloat(response.data['Time Series (Daily)'][date]['4. close']) * 100) / 100,
volume : parseInt(response.data['Time Series (Daily)'][date]['5. volume'])
}
})
})
.then(_ => {
let curValueSchema = new parentSchemaSymbol()
curValueSchema.symbol = curValue;
for(x in highLow){
curValueSchema.data.push(highLow[x])
}
curValueSchema.save().then(doc => {
console.log('Saved the symbol', doc)
return res.send(highLow)
}).catch(e => {
console.log(e)
})
})
.catch(error => {
console.log(error);
})
在模式中,我不知道this.slug = slug(this.symbol)
作用,但是要使用該slug方法,您必須定義或導入它,否則它將導致錯誤,希望這對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.