Как разрешить MissingSchemaError в mongodb с помощью mongoose - PullRequest
0 голосов
/ 30 мая 2020

Я создаю модель 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

1 Ответ

1 голос
/ 30 мая 2020

Вместо mongoose.model(...) нужно подключение к БД 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;
...