我正在尝试将数据发布到在mLab上创建的数据库中,但出现此错误,但我不知道出了什么问题。我也阅读了有关此主题的先前询问的问题,但由于无法解决错误我是新来的。因此,我在这里发布了我要实现的代码,该代码取自本教程https://medium.freecodecamp.com/building- a-simple-node-js-api-in-under-30-minutes- a07ea9e390d2。
server.js
const express = require('express'); const MongoClient = require('mongodb').MongoClient; const bodyParser = require('body-parser'); const db = require('./config/db'); const app = express(); const port = 8000; app.use(bodyParser.urlencoded({extened:true})); MongoClient.connect(db.url,(err,database) =>{ if (err) return console.log(err) require('./app/routes')(app,{}); app.listen(port,() => { console.log("We are live on"+port); }); })
db.js
module.exports = { url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing" };
index.js
const noteroutes = require('./note_routes'); module.exports = function(app,db) { noteroutes(app,db); };
note_routes.js
module.exports = function(app, db) { app.post('/notes', (req, res) => { const note = { text: req.body.body, title: req.body.title }; db.collection('notes').insert(note, (err, result) => { if (err) { res.send({ 'error': 'An error has occurred' }); } else { res.send(result.ops[0]); } }); }); };
在server.js中,您传递了一个空对象,您需要在其中传递数据库作为第二个参数,这是您的route / index.js导出函数所期望的。
PFB更新了server.js:
const express = require('express'); const MongoClient = require('mongodb').MongoClient; const bodyParser = require('body-parser'); const db = require('./config/db'); const app = express(); const port = 8000; app.use(bodyParser.urlencoded({extended:true})); MongoClient.connect(db.url,(err,database) =>{ if (err) return console.log(err) //require('./app/routes')(app,{}); //check below line changed require('./app/routes')(app, database); app.listen(port,() => { console.log("We are live on"+port); }); });