How to save an array of Web Api data to a child - parent schema in a nested mongoose schema?
I am trying to save the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save it under the Child Schema in the database.
How can I do this with nodejs and mongoose? Here is the code that I tried....
Folder - Models - 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)
Controller - 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 result = highLow
javascript node.js express mongoose mongoose-schema
|
show 7 more comments
I am trying to save the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save it under the Child Schema in the database.
How can I do this with nodejs and mongoose? Here is the code that I tried....
Folder - Models - 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)
Controller - 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 result = highLow
javascript node.js express mongoose mongoose-schema
how about you changemodule.exports = mongoose.model('Stock', (childSchemaData, parentSchemaSymbol))
tomodule.exports = mongoose.model('Stock', parentSchemaSymbol)
and savehighLowData
ascurValueSchema.data.push(highLowData)
, see if that helps you
– siddhant sankhe
Nov 15 '18 at 6:12
@siddhantsankhe You mean like thislet highLowData = highLow let curValueSchema = new parentSchemaSymbol({ symbol: curValue, data: [curValueSchema.data.push(highLowData)], slug: String })
It gives me an errorReferenceError: parentSchemaSymbol is not defined at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:34:28) at process._tickCallback (internal/process/next_tick.js:178:7)
– John John
Nov 15 '18 at 6:27
please change statement to thismodule.exports = mongoose.model('Stock', parentSchemaSymbol)
and afterrequire('../models/Stock')
please addvar parentSchemaSymbol = mongoose.model('parentSchemaSymbol');
– siddhant sankhe
Nov 15 '18 at 6:45
You dont need to export subdocument , and mongoose allows only one schema per export , if you are using sub document then it is already present in Parent Document exporting it separately would make whole point of using subdocuments pointless , regards
– siddhant sankhe
Nov 15 '18 at 6:49
@siddhantsankhe you are right , very valid point . I updated the code but still getting the same errorconst parentSchemaSymbol = mongoose.model(parentSchemaSymbol) ^ ReferenceError: parentSchemaSymbol is not defined
– John John
Nov 15 '18 at 6:59
|
show 7 more comments
I am trying to save the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save it under the Child Schema in the database.
How can I do this with nodejs and mongoose? Here is the code that I tried....
Folder - Models - 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)
Controller - 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 result = highLow
javascript node.js express mongoose mongoose-schema
I am trying to save the result of the Web Api which contains multiple arrays of data to populate the stock chart. Each time I enter a symbol and click the "Get Quote" button it should fetch data from the web api, save it under the Child Schema in the database.
How can I do this with nodejs and mongoose? Here is the code that I tried....
Folder - Models - 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)
Controller - 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 result = highLow
javascript node.js express mongoose mongoose-schema
javascript node.js express mongoose mongoose-schema
edited Nov 15 '18 at 8:49
John John
asked Nov 15 '18 at 5:39
John John John John
758
758
how about you changemodule.exports = mongoose.model('Stock', (childSchemaData, parentSchemaSymbol))
tomodule.exports = mongoose.model('Stock', parentSchemaSymbol)
and savehighLowData
ascurValueSchema.data.push(highLowData)
, see if that helps you
– siddhant sankhe
Nov 15 '18 at 6:12
@siddhantsankhe You mean like thislet highLowData = highLow let curValueSchema = new parentSchemaSymbol({ symbol: curValue, data: [curValueSchema.data.push(highLowData)], slug: String })
It gives me an errorReferenceError: parentSchemaSymbol is not defined at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:34:28) at process._tickCallback (internal/process/next_tick.js:178:7)
– John John
Nov 15 '18 at 6:27
please change statement to thismodule.exports = mongoose.model('Stock', parentSchemaSymbol)
and afterrequire('../models/Stock')
please addvar parentSchemaSymbol = mongoose.model('parentSchemaSymbol');
– siddhant sankhe
Nov 15 '18 at 6:45
You dont need to export subdocument , and mongoose allows only one schema per export , if you are using sub document then it is already present in Parent Document exporting it separately would make whole point of using subdocuments pointless , regards
– siddhant sankhe
Nov 15 '18 at 6:49
@siddhantsankhe you are right , very valid point . I updated the code but still getting the same errorconst parentSchemaSymbol = mongoose.model(parentSchemaSymbol) ^ ReferenceError: parentSchemaSymbol is not defined
– John John
Nov 15 '18 at 6:59
|
show 7 more comments
how about you changemodule.exports = mongoose.model('Stock', (childSchemaData, parentSchemaSymbol))
tomodule.exports = mongoose.model('Stock', parentSchemaSymbol)
and savehighLowData
ascurValueSchema.data.push(highLowData)
, see if that helps you
– siddhant sankhe
Nov 15 '18 at 6:12
@siddhantsankhe You mean like thislet highLowData = highLow let curValueSchema = new parentSchemaSymbol({ symbol: curValue, data: [curValueSchema.data.push(highLowData)], slug: String })
It gives me an errorReferenceError: parentSchemaSymbol is not defined at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:34:28) at process._tickCallback (internal/process/next_tick.js:178:7)
– John John
Nov 15 '18 at 6:27
please change statement to thismodule.exports = mongoose.model('Stock', parentSchemaSymbol)
and afterrequire('../models/Stock')
please addvar parentSchemaSymbol = mongoose.model('parentSchemaSymbol');
– siddhant sankhe
Nov 15 '18 at 6:45
You dont need to export subdocument , and mongoose allows only one schema per export , if you are using sub document then it is already present in Parent Document exporting it separately would make whole point of using subdocuments pointless , regards
– siddhant sankhe
Nov 15 '18 at 6:49
@siddhantsankhe you are right , very valid point . I updated the code but still getting the same errorconst parentSchemaSymbol = mongoose.model(parentSchemaSymbol) ^ ReferenceError: parentSchemaSymbol is not defined
– John John
Nov 15 '18 at 6:59
how about you change
module.exports = mongoose.model('Stock', (childSchemaData, parentSchemaSymbol))
to module.exports = mongoose.model('Stock', parentSchemaSymbol)
and savehighLowData
as curValueSchema.data.push(highLowData)
, see if that helps you– siddhant sankhe
Nov 15 '18 at 6:12
how about you change
module.exports = mongoose.model('Stock', (childSchemaData, parentSchemaSymbol))
to module.exports = mongoose.model('Stock', parentSchemaSymbol)
and savehighLowData
as curValueSchema.data.push(highLowData)
, see if that helps you– siddhant sankhe
Nov 15 '18 at 6:12
@siddhantsankhe You mean like this
let highLowData = highLow let curValueSchema = new parentSchemaSymbol({ symbol: curValue, data: [curValueSchema.data.push(highLowData)], slug: String })
It gives me an error ReferenceError: parentSchemaSymbol is not defined at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:34:28) at process._tickCallback (internal/process/next_tick.js:178:7)
– John John
Nov 15 '18 at 6:27
@siddhantsankhe You mean like this
let highLowData = highLow let curValueSchema = new parentSchemaSymbol({ symbol: curValue, data: [curValueSchema.data.push(highLowData)], slug: String })
It gives me an error ReferenceError: parentSchemaSymbol is not defined at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:34:28) at process._tickCallback (internal/process/next_tick.js:178:7)
– John John
Nov 15 '18 at 6:27
please change statement to this
module.exports = mongoose.model('Stock', parentSchemaSymbol)
and after require('../models/Stock')
please add var parentSchemaSymbol = mongoose.model('parentSchemaSymbol');
– siddhant sankhe
Nov 15 '18 at 6:45
please change statement to this
module.exports = mongoose.model('Stock', parentSchemaSymbol)
and after require('../models/Stock')
please add var parentSchemaSymbol = mongoose.model('parentSchemaSymbol');
– siddhant sankhe
Nov 15 '18 at 6:45
You dont need to export subdocument , and mongoose allows only one schema per export , if you are using sub document then it is already present in Parent Document exporting it separately would make whole point of using subdocuments pointless , regards
– siddhant sankhe
Nov 15 '18 at 6:49
You dont need to export subdocument , and mongoose allows only one schema per export , if you are using sub document then it is already present in Parent Document exporting it separately would make whole point of using subdocuments pointless , regards
– siddhant sankhe
Nov 15 '18 at 6:49
@siddhantsankhe you are right , very valid point . I updated the code but still getting the same error
const parentSchemaSymbol = mongoose.model(parentSchemaSymbol) ^ ReferenceError: parentSchemaSymbol is not defined
– John John
Nov 15 '18 at 6:59
@siddhantsankhe you are right , very valid point . I updated the code but still getting the same error
const parentSchemaSymbol = mongoose.model(parentSchemaSymbol) ^ ReferenceError: parentSchemaSymbol is not defined
– John John
Nov 15 '18 at 6:59
|
show 7 more comments
1 Answer
1
active
oldest
votes
Please have a look at your axios request call , and change it to this
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);
})
And in Schema i dont know what this.slug = slug(this.symbol)
this does , but to use that slug method u must define it or import it , otherwise it will just give to errors , hope this helps you
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53313083%2fhow-to-save-an-array-of-web-api-data-to-a-child-parent-schema-in-a-nested-mong%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Please have a look at your axios request call , and change it to this
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);
})
And in Schema i dont know what this.slug = slug(this.symbol)
this does , but to use that slug method u must define it or import it , otherwise it will just give to errors , hope this helps you
add a comment |
Please have a look at your axios request call , and change it to this
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);
})
And in Schema i dont know what this.slug = slug(this.symbol)
this does , but to use that slug method u must define it or import it , otherwise it will just give to errors , hope this helps you
add a comment |
Please have a look at your axios request call , and change it to this
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);
})
And in Schema i dont know what this.slug = slug(this.symbol)
this does , but to use that slug method u must define it or import it , otherwise it will just give to errors , hope this helps you
Please have a look at your axios request call , and change it to this
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);
})
And in Schema i dont know what this.slug = slug(this.symbol)
this does , but to use that slug method u must define it or import it , otherwise it will just give to errors , hope this helps you
answered Nov 15 '18 at 7:58
siddhant sankhesiddhant sankhe
33339
33339
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53313083%2fhow-to-save-an-array-of-web-api-data-to-a-child-parent-schema-in-a-nested-mong%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
how about you change
module.exports = mongoose.model('Stock', (childSchemaData, parentSchemaSymbol))
tomodule.exports = mongoose.model('Stock', parentSchemaSymbol)
and savehighLowData
ascurValueSchema.data.push(highLowData)
, see if that helps you– siddhant sankhe
Nov 15 '18 at 6:12
@siddhantsankhe You mean like this
let highLowData = highLow let curValueSchema = new parentSchemaSymbol({ symbol: curValue, data: [curValueSchema.data.push(highLowData)], slug: String })
It gives me an errorReferenceError: parentSchemaSymbol is not defined at axios.get.then.then._ (/mnt/c/Users/john/Desktop/node/controllers/webApiController.js:34:28) at process._tickCallback (internal/process/next_tick.js:178:7)
– John John
Nov 15 '18 at 6:27
please change statement to this
module.exports = mongoose.model('Stock', parentSchemaSymbol)
and afterrequire('../models/Stock')
please addvar parentSchemaSymbol = mongoose.model('parentSchemaSymbol');
– siddhant sankhe
Nov 15 '18 at 6:45
You dont need to export subdocument , and mongoose allows only one schema per export , if you are using sub document then it is already present in Parent Document exporting it separately would make whole point of using subdocuments pointless , regards
– siddhant sankhe
Nov 15 '18 at 6:49
@siddhantsankhe you are right , very valid point . I updated the code but still getting the same error
const parentSchemaSymbol = mongoose.model(parentSchemaSymbol) ^ ReferenceError: parentSchemaSymbol is not defined
– John John
Nov 15 '18 at 6:59