0

I am creating a schema model dynamically. So I am not able to use this model for other events like a record save, update, remove, etc. If I use that I am getting this error:

Error: MissingSchemaError: Schema hasn't been registered for model "XYZ". Use mongoose.model(name, schema)

I do not know why it is coming to this error. I have tried many times but not working. Please help to resolve this issue?

schemamodel.js:

    /* model.js */
 'use strict';
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;

 function dynamicModel(suffix) {
     var collsName = suffix.charAt(0).toUpperCase() + suffix.slice(1);
     var newSchema = new Schema({
         product_name: {
             type: String
         }
     }, {
         versionKey: false
     });
     try {
         if (mongoose.model(collsName)) return mongoose.model(collsName);
     } catch (e) {
         if (e.name === 'MissingSchemaError') {
             return mongoose.model(collsName, newSchema, suffix);
         }
     }
 }
 module.exports = dynamicModel;

data.controller.js:

module.exports.newCollection = (req, res, next) => {
    var collectionName = req.query.collectionName;
    var NewModel;
    mongoose.connection.db.listCollections().toArray(function(err, names) {
        if (err) {
            console.log(err);
        } else {
            names.forEach(function(e, i, a) {
                if (e.name == collectionName.toLowerCase()) {
                    console.log("The collection already exists");
                } else {
                    console.log("The collection not exists");
                    NewModel = require(path.resolve('./models/schemamodel.js'))(collectionName);
                    NewModel.create({}, function(err, doc) {});
                }
            });
        }
    });
}
//get data collection from collection 
module.exports.getCollectionData = (req, res, next) => {
    let collection = req.query.collection;
    let data = mongoose.model(collection); // here getting MissingSchemaError
    data.find({}, function(err, docs) {
        if (err) {
            console.log('ss' + err);
            return;
        } else {
            console.log("Successful loaded");
        }
    });
}

api call:

http://localhost:3000/api/getCollectionData?collection=Apply
Pappa S
  • 303
  • 1
  • 8
  • 21

1 Answers1

1

Instead of mongoose.model(...) you need the DB connection db.model(...)

 /* model.js */
 'use strict';
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;
 const db = mongoose.createConnection(
      "mongodb://localhost:27017/datadetails",
      {
        useNewUrlParser: true,
        useUnifiedTopology: true
      }
  );
 function dynamicModel(suffix) {
     var collsName = suffix.charAt(0).toUpperCase() + suffix.slice(1);
     var newSchema = new Schema({
         product_name: {
             type: String
         }
     }, {
         versionKey: false
     });
     try {
         if (db.model(collsName)) return db.model(collsName);
     } catch (e) {
         if (e.name === 'MissingSchemaError') {
             return db.model(collsName, newSchema, suffix);
         }
     }
 }
 module.exports = dynamicModel;
bill.gates
  • 14,145
  • 3
  • 19
  • 47