Rhod Rhod - 2 months ago 7
Node.js Question

How would I create and update a time series using mongoose?

I would like to follow this schema design as it seems well though out: http://blog.mongodb.org/post/65517193370/schema-design-for-time-series-data-in-mongodb

Ideally, I would like to record documents that capture data every second for a minute - just like in their early example.

I've run into 3 different hurdles:

1) I'm not quite sure how the schema should look - at the moment I have something like so:

var mySchema = new mongoose.Schema({
timestamp_minute: String,
type: String,
values: [ Number ]
});


2) The 'values' array should be of length 60 (to store our one second data interval data points over a minute). How would I go about pre-populating this array with 0s?

3) How do I go about updating this array. I guess in my Node.js as I am getting frequent and consistent updates on the second, I could just use a index that gets increment and then resets after 59. Is there a way to use this index when trying to access 'values', e.g. using a mongoose update and '$set: { 'values.' + index: myValue }'?

Answer
  1. Your schema should be:

    var mySchema = new mongoose.Schema({
      timestamp_minute: Date,
      type: String,
      values: [ Number ]
    });

  1. You don't have to pre-populate it. In js, you can set any index you want even if the array is empty. However, if you want to do it:

var mySchema = new mongoose.Schema({
      timestamp_minute: Date,
      type: String,
      values: {
        type: [ Number ],
        default: function() { return Array(60).fill(0); }
      }
    });

  1. Yes. This is the way to do it as you see in the article.