NodeJS Mongo - Mongoose - Dynamic collection name


Hello you just need to declare schema model with your dinamically name, like this:

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

// our schema 

function dynamicSchema(prefix){
    var addressSchema = new Schema({
        dir : {type : String, required : true},    //los 2 nombres delimitados por coma (,) ej. Alberto,Andres
        city : {type : String, required: true},   //la misma estructura que para los nombres ej. Acosta, Arteta 
        postal : {type : Number, required : true},
        _home_type : {type : Schema.Types.ObjectId, required : true, ref : prefix + '.home_type'},
        state : {type : String, required : true},
        telefono : String,
        registered : {type : Date, default: Date.now }
    });
    return mongoose.model(prefix + '.address', addressSchema);
}

//no we export dynamicSchema function
module.exports = dynamicSchema;

so in your code anywhere you can do this:

var userAdress = require('address.js')(id_user);
var usrAdrs1 = new userAddress({...});
    userAdrs1.save();

Now go to your mongo shell & list collections (use mydb then show collections), you will see a new collection for address with uid prefix. In this way mongoose will create a new one collection address for each different user uid.


Use the function to get the model dynamically.

/* 
 * Define Schemas as you used to 
 */
const ConvForUserSchema = new Schema({
    user_id: Number,
    conv_hash: String,
    archived: Boolean,
    unread: Boolean
},{
    versionKey : false,
    strict: false
});

/*
 * Define the dynamic function
 */
const models = {};
const getModel = (collectionName) => {
    if( !(collectionName in models) ){
        models[collectionName] = connection.model(
            collectionName, ConvForUserSchema, collectionName
        );
    }
    return models[collectionName];
};

Then get the dynamic model using the function

const result = getModel("YourCollectionName").findOne({})