Node.js 如何使用mongoose解决mongodb中的MissingSchemaError
我正在动态创建一个Node.js 如何使用mongoose解决mongodb中的MissingSchemaError,node.js,mongodb,mongoose,mongodb-query,Node.js,Mongodb,Mongoose,Mongodb Query,我正在动态创建一个模式模型。因此,我无法将此模型用于其他事件,如记录保存、更新、删除,等等。如果我使用此模型,我将收到此错误: 错误:缺少架构错误:尚未为模型注册架构 “XYZ”。使用mongoose.model(名称、模式) 我不知道为什么会出现这种错误。我试了很多次,但都没有成功。请帮助解决此问题 schemamodel.js: /* model.js */ 'use strict'; var mongoose = require('mongoose'), Schema
模式
模型。因此,我无法将此模型
用于其他事件,如记录保存、更新
、删除
,等等。如果我使用此模型,我将收到此错误:
错误:缺少架构错误:尚未为模型注册架构
“XYZ”。使用mongoose.model(名称、模式)
我不知道为什么会出现这种错误。我试了很多次,但都没有成功。请帮助解决此问题
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
您需要的不是
mongoose.model(…)
而是数据库连接DB.model(…)
@PappaS您的mongodb安装在哪里?它是群集还是在本地运行?Mongodb运行locally@PappaS它应该是这样的
mongodb://localhost:27017/myapp
@PappaS其中myapp
是您的数据库名这是我的数据库url:mongodb://localhost:27017/datadetails
/* 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;