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