In MongoDB, time series collections are data structures specifically designed for storing and managing time series data. Mongoose is an Object Data Modeling (ODM) library for MongoDB that simplifies working with MongoDB databases in Node.js environments. Although Mongoose does not natively provide a method for creating time series collections, we can create a time series collection using MongoDB's native operations and then interact with it via Mongoose.
Step 1: Creating a Time Series Collection
First, you should directly use MongoDB's shell or programming interface to create a time series collection. In MongoDB 5.0 and later versions, you can specify a collection as a time series type when creating it. Here is an example of creating a time series collection using MongoDB shell:
bashdb.createCollection("temperatures", { timeseries: { timeField: "timestamp", granularity: "hours" } });
In this example, we create a time series collection named temperatures, specifying timestamp as the time field and setting the time granularity to hours.
Step 2: Defining the Model in Mongoose
Once the time series collection is created, you can define a model in Mongoose to interact with it. Here is an example of defining this model:
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; const temperatureSchema = new Schema({ timestamp: Date, value: Number }, { timestamps: false, // Disable Mongoose's automatic timestamps since we are using MongoDB's time series feature collection: 'temperatures' // Specify the collection name for this model }); const Temperature = mongoose.model('Temperature', temperatureSchema);
Step 3: Using the Model to Access Data
Now you can use the defined Mongoose model to access time series data. For example, inserting a new data point:
javascriptconst newTemp = new Temperature({ timestamp: new Date(), value: 23.5 }); newTemp.save().then(doc => { console.log('New temperature record saved:', doc); }).catch(err => { console.error('Error saving record:', err); });
Summary
By doing this, we leverage MongoDB's native capabilities to create time series collections and use Mongoose's convenient interface for data operations and management. Although it is not done directly through Mongoose, this approach effectively combines the strengths of both.