Reputation: 829
null
upon instantiation?I have a Mongodb collection of timeseries where values are stored in a fixed-length array (1 item per minute, 1 document per day).
{
'series': '#1',
'values': [null, null, 1, 2, 3, -4, ... ] //24h*60min=1440 items
}
I am doing computations on ~x000 timeseries on a rather high frequency (100ms), and I want to store the maximum that each of these series met during every minute. For some reason, when I update the documents, Mongoose transforms the .values
property into an object, which is more space-consuming and less efficient for my use.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test_db');
const TestSchema = new mongoose.Schema({
series: String,
values: {type: Array, default: Array(5).fill(null), required: true},
});
const Test = mongoose.model('Test', TestSchema);
async function update({series, values}){ //called every minute or so
let updated = { };
for (let {i, v} of values) {
if (updated[`values.${i}`] && updated[`values.${i}`]<v) updated[`values.${i}`]= v;
if (!updated[`values.${i}`]) updated[`values.${i}`]=v;
};
return mongoose.connection.models.Test.updateOne(
{'series':series},
{ '$max': updated },
{ upsert: true, strict: true, new: true}
);
}
async function test_update(){
//get rid of previous tentatives
await mongoose.connection.models.Test.deleteMany({});
let s = new Test({series: '#1'});
await update({series:'#1', values:[{i:3, v:-3},{i:4, v:6},{i:2, v:4}, {i:2, v:7}]});
}
test_update();
I would want my script to return
{
"_id" : ObjectId("5cb351d9d615cd456bd6a4ed"),
"series" : "#1",
"__v" : 0,
"values" : [null, null, 7, -3, 6]
}
and not the current result below:
{
"_id" : ObjectId("5cb351d9d615cd456bd6a4ed"),
"series" : "#1",
"__v" : 0,
"values" : { //values is an Object, not an Array
"2" : 7,
"3" : -3,
"4" : 6
}
}
Thanks!
Upvotes: 1
Views: 52
Reputation: 206
`I THINK it may be your schema
Instead of:
const TestSchema = new mongoose.Schema({
series: String,
values: {type: Array, default: Array(5).fill(null), required: true},
});
You should make values
an array of numbers like this
const TestSchema = new mongoose.Schema({
series: String,
values: {type: [Number], default: Array(5).fill(null), required: true},
});
Upvotes: 1