0

How to create a new collection on every POST request on NodeJS express + mongoose based REST API ?

There are lot of tutorials that uses the same collection hard-coded, but can't find one which allows to create new collection on every new POST.

For example: model.js

var mongoose = require('mongoose');
var mySchema = new mongoose.Schema({
       //Scehma Here
});
module.exports = mongoose.model('mycollection', mySchema);

and server.js

var devices = require('./model');
router.route('/devices')
  .post(function(req, res) {
    var device = new devices();
        device._id = req.body.id;
        device.save(function(err) {
            if (err)
              res.send(err);
            res.json({ message: 'Success!' });
        });
  })

This creates new document on the mycollection for every new POST

But, I need to isolate every new object created in to a new collection.

Is it possible to create a new collection on every POST with the same schema and collection name being req.body.id

Update:

Usecase for @chridam and @MykolaBorysyuk comments

The data will be timeseries data from lot of IoT devices.

On the first connect, the device will do a POST request with its ID like IMEI and from then it will send data continuously every 5 secs. To store something like here: http://blog.mongodb.org/post/65517193370/schema-design-for-time-series-data-in-mongodb

I thought creating a new collection for each device will be good idea, if thats a bad choice (I'm DevOps and new to Development), please suggest me a better approach for the above use case. It will be 100s of devices with continuous time series data.

Thank you.

Community
  • 1
  • 1
Shan
  • 2,141
  • 2
  • 17
  • 32
  • 2
    Just being curious, why would you want to create a collection for each HTTP POST request? – chridam Sep 12 '16 at 07:19
  • have you tried this http://stackoverflow.com/questions/15306916/dynamically-create-collection-w-mongoose – Mohammad Sayeed Sep 12 '16 at 07:52
  • Basically you can using mongoDb driver. But it's very bad approach. You may want to rethink your logic and find better solution. – Mykola Borysyuk Sep 12 '16 at 07:53
  • Thanks @MykolaBorysyuk Updated the question with use case, please suggest me a better approach for the same I'm new to NodeJS and NoSQL DBs – Shan Sep 12 '16 at 10:53
  • If you can that just make in mongo _id = thatDeviceUniqueId and store that values there. So you will have documents something like this {_id: deviceId, data: [Array of that data that you want..]}. And just on each post update data array – Mykola Borysyuk Sep 12 '16 at 16:31
  • @MykolaBorysyuk Thanks, let me try that – Shan Sep 13 '16 at 16:06

1 Answers1

0

I think @MykolaBorysyuk suggestion is valid but if you would want to use capped collections to limit the number of documents that will be kept per device then separate collections is the better approach.

ipopa
  • 1,223
  • 11
  • 12