我在nodeJS上有一个当前正在运行的应用程序,并且正在连接到mongoDB。
这是我的router.js
var mongoose = require('mongoose')
, connection = require('../connection')
, Connection = mongoose.connection
, express = require('express')
, router = express.Router()
// router information
router.get('/', function(req, res) {
Connection.db.collection("users", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // it will print your collection data
res.render('../views/pages/index.ejs',{data:data});
})
});
});
// add data
router.post('/add',function(req, res){
var myobj = {name:"batman", email:"batman.com", occupation:"IT director", username:"batman"};
Connection.db.collection("users", function(err, collection){
collection.insertOne(myobj, function(err){
});
});
});
module.exports = router
这是我的connection.js
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/user', { useMongoClient: true },function () {
console.log('mongodb connected')
})
module.exports = mongoose
这是我的app.js
var mongoose = require('mongoose')
, bodyParser = require('body-parser')
, PORT = 4000
, instantMongoCrud = require('express-mongo-crud') // require the module
, options = { //specify options
host: `localhost:${PORT}`
}
, route = require('./routes/router')
, express = require('express')
, app = express()
//USE AS MIDDLEWARE
app.use(bodyParser.json()); // add body parser
app.use(instantMongoCrud(options)); // use as middleware
// routes
app.use('/', route)
app.listen(PORT, ()=>{
console.log('started');
})
我的router.get工作正常,并且能够在index.ejs中显示数据。但是,对于我的add函数,它总是抛出
MissingSchemaError: Schema hasn't been registered for model "add".
Use mongoose.model(name, schema)
我不明白为什么这种方法不起作用,因为已经声明了我的模式,并且能够查询出数据。插入不起作用,但是我不确定为什么。
有任何可用的帮助吗?