【问题标题】:How to get data from mongodb for dynamically created schema model如何从 mongodb 获取动态创建的模式模型的数据
【发布时间】:2020-09-22 00:16:55
【问题描述】:

我正在尝试从 mongodb 获取数据但不能。因为下面的错误是原因。我通过动态创建模式模型将数据插入到 mongodb。所以我无法从 mongodb 获取数据。如何从 mongodb 获取数据以进行(动态创建模式)集合?请帮助任何人。我在谷歌搜索过但没有用。

MissingSchemaError:尚未为模型“Tea”注册架构。 在 Mongoose.model 中使用 mongoose.model(name, schema)

createschema.js

const db = mongoose.createConnection(
     "mongodb://localhost:27017/products", {
         useNewUrlParser: true,
         useUnifiedTopology: true
     }
 );

 function dynamicModel(suffix) {
     var collsName = suffix.charAt(0).toUpperCase() + suffix.slice(1);
     var collsSmall = suffix.toLowerCase();
     var newSchema = new Schema({
         pid: {
             type: String
         },
         product_name: {
             type: String
         },
         product_price: {
             type: Number
         } 
     }, {
         versionKey: false,
         collection: collsSmall
     });
     try {
         if (db.model(collsName)) return db.model(collsName);
     } catch (e) {
         if (e.name === 'MissingSchemaError') {
             return db.model(collsName, newSchema, collsSmall);
         }
     }
 }

 module.exports = dynamicModel;

data.controller.js:

const mongoose = require('mongoose');
module.exports.getCollectionData = (req, res, next) => {
    let collection = req.query.collection;
    let tabledata = mongoose.model(collection); //Got MissingSchemaError  
    tabledata.find({}, function(err, docs) {
        if (err) {
            console.log(err);
            return;
        } else {
            res.json({ data: docs, success: true, msg: 'Products data loaded.' });
        }
    })
}

//Create model
module.exports.newCollection = (req, res, next) => {
    var collectionName = req.query.collectionName;
    var NewModel = require(path.resolve('./models/createschema.model.js'))(collectionName);           
    NewModel.create({ }, function(err, doc) {});
}

db.js:

const mongoose = require('mongoose'); 
mongoose.connect(process.env.MONGODB_URI, (err) => {
    if (!err) { console.log('MongoDB connection succeeded.'); } else { console.log('Error in MongoDB connection : ' + JSON.stringify(err, undefined, 2)); }
}); 
require('./createschema.model');

api 调用:

     http://localhost:3000/api/getCollectionData?collection='Tea'

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    在函数getCollectionData 中尝试db.model 而不是mongoose.model 由于您在特定的 connection 上创建了 collection,因此您也必须使用相同的 connection 来获取 model

    const db = mongoose.createConnection(
     "mongodb://localhost:27017/products", {
         useNewUrlParser: true,
         useUnifiedTopology: true
     }
    );
    
    module.exports.getCollectionData = (req, res, next) => {
        let collection = req.query.collection;
        let tabledata = db.model(collection); //Change here  
        tabledata.find({}, function(err, docs) {
            if (err) {
                console.log(err);
                return;
            } else {
                res.json({ data: docs, success: true, msg: 'Products data loaded.' });
            }
        })
    }
    

    【讨论】:

    • 我又遇到了同样的错误:MissingSchemaError: Schema还没有为模型“Tea”注册。使用 mongoose.model(name, schema)
    • 你还有什么想法吗?
    • 我已经添加了我的 db.js..你能检查一下吗?
    【解决方案2】:
    1. 你从根本上滥用了mongoose.model() / connection.model()

      这个函数只能用于创建一个新的猫鼬模型,使用 所需的模型名称和架构定义参数。

    2. createschema.js 中,当您有try {if (db.model(collsName)) return db.model(collsName);} catch 时,您不会检查模型 已经存在。 db.model(collsName) 总是会抛出错误 因为您没有提供带有架构的第二个必需参数 定义。

      我想您正在尝试检查模型是否已经存在,如果存在 把它返还。请参阅documentation for Connection.prototype.models。上面的片段应该 因此是:

    try {
       // db is an instance of mongoose.Connection    
       let existingModel = db.models[collsName];   
       if (existingModel) return existingModel; 
    } catch 
    
    1. 同样在data.controller.js getCollectionData 目前你是 调用一个方法来创建一个新的猫鼬模型'mongoose.model()', 但不提供架构(因此会出现 MissingSchemaError)

    你需要任何一个

    • 从 mongoose 实例中获取模型(如果您似乎暗示已经注册)
    let tabledata = mongoose.connection.models[collection];
    

    • 创建一个新的猫鼬模型
    const dynamicModel = require('./createschema.js');
    let tabledata =
    dynamicModel(collection)
    

    【讨论】:

    • Getting TypeError: Cannot read property 'create' of undefined in this line NewModel.create({ }, function(err, doc) {});
    • 我已经改变了你的代码,比如 try { let existingModel = db.models[collsName]; if (existingModel) {return existingModel;}else{return db.model(collsName, newSchema, collsSmall); } } catch 那么只有它在工作..我认为这是正确的方法仪式?
    猜你喜欢
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多