如何从 mongodb 获取动态创建的模式模型的数据



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

Missing SchemaError: 尚未为模型"Tea"注册架构。 在Mongoose.model上使用mongoose.model(name,schema(

创建架构.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) {});
}

分贝.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');

接口调用:

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

尝试在函数getCollectionDatadb.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.' });
}
})
}
  1. 你从根本上滥用了mongoose.model()/connection.model()

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

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

    我假设您正在尝试检查模型是否已经存在,如果是的话 归还它。请参阅文档 上面的片段应该 因此是:

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

您需要

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

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

最新更新