LAX_DEV
LAX_DEV

Reputation: 2271

Mongoose dynamic mongodb collection name

I am using mongoose driver for mongodb on node.js. I have a schema as below.

Using db.model I can get the model with the hardcoded collection name "aggregation". It works fine.

But how do I use the schema/model with a dynamic on-demand collection name? Basically, I will need to define a new collection on-demand and it will use the same schema.

aggregationmodel.js

var mongoose    = require('mongoose');

var db = mongoose.createConnection(configfile.mongodb.uriAggregation);

var aggregationSchema = mongoose.Schema({

    factorname   : { type: String, index: true },
    active       : { type: Boolean},

    total   : [{
            _id : { type: Number, index: true },
            ordervolume : Number,
            ordertips : Number,
            ordernationality : String,
            ordercancelled : Number
           }
          ]    
});

module.exports = db.model('aggregation', aggregationSchema, 'aggregation');

controller.js (this file references to model)

var Aggregates     = require('../models/aggregationmodel.js');

Upvotes: 3

Views: 4566

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

All you basically need to do in instantiate a "new" model which has the required collection as an argument. It's just a matter of scoping really as to if the schema is available. But you can always get the schema from an existing model and use in in the new instance:

var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/modtest');

var testSchema = new Schema({},{ strict: false });

var Test = mongoose.model( "Test", testSchema, "test" );


mongoose.connection.on("open", function(err,conn) {

  var ReModel = mongoose.model( "Redo", Test.schema, "redo" );

  var redo = new ReModel({ "a": 1 });

  redo.save(function(err,doc) {
    if (err) throw err;
    console.log( doc );
    console.log( "done" );
  });


});

The result there is that the actual document is inserted in the collection tied to the model you instantiated based on the schema extracted from the other model instance.

All you really need to do in your implementation is the same thing and supply the desired collection as an argument to feed into the standard instance creation method.

Upvotes: 3

Related Questions