Skip to content

Instantly share code, notes, and snippets.

@parthi2929
Last active January 11, 2018 14:56
Show Gist options
  • Save parthi2929/0eb2ec94698c278bd1409ce7b559d32a to your computer and use it in GitHub Desktop.
Save parthi2929/0eb2ec94698c278bd1409ce7b559d32a to your computer and use it in GitHub Desktop.
File to push OHLC data to data array (working with ugly work around : separate schema for read)
var mongoose = require('mongoose');
var ohlcSchema = mongoose.Schema(
{
_id:{type: Number, unique: true},
data: [Number]
},
{
collection:'ohlc-min-DB'
}
);
var ohlcSchemaRead = mongoose.Schema(
{
_id:{type: Number, unique: true},
data: [[Number]]
},
{
collection:'ohlc-min-DB'
}
);
var ohlcModel = mongoose.model('ohlcModel', ohlcSchema);
var ohlcModelRead = mongoose.model('ohlcModelRead', ohlcSchemaRead);
mongoose.connect(
'mongodb://localhost:27017/test',
{
useMongoClient:true
}
);
var myDBConnection = mongoose.connection;
//open the DB
myDBConnection.once(
'open',
function()
{
//update the record with new data - THIS IS WORKING
ohlcModel.findOneAndUpdate(
{ _id:1},
{ $push: { 'data': [1234,23,2352,123,523,23523] } },
{ upsert: true },
function(error, result)
{
if(error) console.log('Error appending: ' + error);
else console.log('Data Successfully appended: ' + result); //VERY FIRST TIME RETURNS NULL THOUGH DATA APPENDED WHICH IS WRONG
}
);
//retrieve entire latest data - THIS IS WORKING BUT UGLY WITH ANOTHER SCHEMA
ohlcModelRead.findOne({_id:1},
function(error, result)
{
if(error) console.log('Error retrieving: ' + error);
else
{
console.log('Existing Data: ' + result.data);
console.log('Existing Data Rows: ' + result.data.length);
console.log('Existing Data Columns: ' + result.data[0].length);
}
}
);
}
);
//Exit automatically after a while
setTimeout(
function()
{
mongoose.disconnect();
},
3000
);
@parthi2929
Copy link
Author

Data updated successfully, cross verified in mongodb client console, but retrieving returns empty value.

@parthi2929
Copy link
Author

parthi2929 commented Jan 11, 2018

Rev 4 and 5, I included another schema for reading, which is working, but this is ugly work around. How do we handle in single schema?

@dnickless
Copy link

You should only need to use the second ("ohlcSchemaRead") schema, also for updates.

@parthi2929
Copy link
Author

When I use only the second one for both read and write, the data is written like below with each element stored as array inside array of array!
{"data" : [ [ [1321523, 23, 52], [12], [523], [5234] ], [ [1321523], [23], [52], [12], [523], [5234] ] ] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment