如何从 mongodb 获取动态创建的模式模型的数据 [英] How to get data from mongodb for dynamically created schema model
问题描述
我正在尝试从 mongodb 获取数据,但没有.因为下面的错误是原因.我通过动态创建模式模型将数据插入到mongodb中.所以我无法从mongodb获取数据.如何从mongodb获取数据以进行(动态创建模式)集合?请帮助任何人.我在谷歌搜索过但没有用.
I am trying to get data from mongodb but could not. Because below the error is the reason.I have inserted data into mongodb by dynamically creating schema model.So I am not able to get data from mongodb.How to get data from mongodb for (dynamically creating schema) collection? Please help anyone.I have searched in google but no use.
MissingSchemaError:尚未为模型Tea"注册架构.在 Mongoose.model 使用 mongoose.model(name, schema)
MissingSchemaError: Schema hasn't been registered for model "Tea". Use mongoose.model(name, schema) at Mongoose.model
createschema.js
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:
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'
推荐答案
你从根本上滥用了
mongoose.model()
/connection.model()
.
这个函数只能用于创建一个新的猫鼬模型,使用必需的模型名称和架构定义参数.
This function can ONLY be used to CREATE a NEW mongoose model using required model name and schema deffinition parameters.
在 createschema.js
中,当你有 try {if (db.model(collsName))return db.model(collsName);} catch
你不是在检查模型已经存在.db.model(collsName)
总是会抛出错误因为您没有为架构提供第二个必需参数定义.
In createschema.js
when you have try {if (db.model(collsName))
return db.model(collsName);} catch
you are NOT checking if model
already exists. db.model(collsName)
will always throw an error
because you are not providing second required parameter with schema
definition.
我想您正在尝试检查模型是否已经存在,如果存在把它返还.请参阅文档连接.原型.模型.上面的片段应该因此是:
I presume you are trying to check if model already exists and if so return it. Please see documentation for Connection.prototype.models. the fragment above should therefore be:
try {
// db is an instance of mongoose.Connection
let existingModel = db.models[collsName];
if (existingModel) return existingModel;
} catch
- 同样在
data.controller.js
getCollectionData
当前你是调用一个方法来创建一个新的猫鼬模型 'mongoose.model()',但不要提供架构(因此您会收到 MissingSchemaError)
- Likewise in
data.controller.js
getCollectionData
currently you are calling a method to create a new mongoose model 'mongoose.model()', but don't provide a schema (hence why you get MissingSchemaError)
你需要要么
- 从猫鼬实例中获取模型(如果您似乎暗示已经注册了)
let tabledata = mongoose.connection.models[collection];
或
- 创建一个新的猫鼬模型
const dynamicModel = require('./createschema.js');
let tabledata =
dynamicModel(collection)
这篇关于如何从 mongodb 获取动态创建的模式模型的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!