我正在尝试从mongodb获取数据,但不能。因为下面是错误原因,我是通过动态创建模式模型将数据插入到mongodb中的,所以我无法从mongodb中获取数据,如何从mongodb中获取数据(用于动态创建模式)集合?请帮助任何人。我已经在Google中搜索过,但没有用。
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:
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/newmodelschema.model.js'))(collectionName);
NewModel.create({ }, function(err, doc) {});
}
api呼叫:
http://localhost:3000/api/getCollectionData?collection='Tea'
尝试使用功能db.model
中的mongoose.model
而不是getCollectionData
由于您是在特定的collection
上创建connection
的,因此您还必须使用相同的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.' });
}
})
}