Я создаю модель schema
динамически. Поэтому я не могу использовать этот model
для других событий, таких как запись save
, update
, remove
и т.д. c. Если я использую это, я получаю эту ошибку:
Ошибка: MissingSchemaError: Схема не была зарегистрирована для модели «XYZ». Используйте mon goose .model (name, schema)
Я не знаю, почему доходит до этой ошибки. Я много раз пробовал, но не работал. Пожалуйста, помогите решить эту проблему?
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:
http://localhost:3000/api/getCollectionData?collection=Apply