Node js&mongoDB – TypeError:db.collection不是一个函数

我想从POSTMAN发布数据到我在mLab创build的外部数据库,但我得到的错误db.collection不是一个函数。

有一个类似的问题线程,但答案是不完整的,并没有保存我把邮递员mLab的任何键/值。 我正在努力的代码是从这个教程: https : //medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2

我的代码:

Server.js

const express = require('express'); // Load routes application const MongoClient = require('mongodb').MongoClient; //Load database connection application const db = require('./config/db'); const app = express(); // Assign express app a variable const port = 8000; //Set local port value for server const bodyParser = require('body-parser'); // **This has to come BEFORE routes var assert = require('assert'); // ? var databaseURL ='mongodb://external:api@ds123312.mlab.com:23312/soundfactory'; app.listen(port, () => { console.log('') console.log('We are live on ' + port); console.log('') }); MongoClient.connect(databaseURL, function(err, db) { assert.equal(null, err); console.log("API has succesfully connected to Sound Facotry mlab external database."); console.log('') db.close(); }); app.use(bodyParser.urlencoded({ extended: true })) require('./app/routes')(app, {}); //Must come AFTER express w/ body parser 

db.js

 module.exports = { url : 'mongodb://external:api@ds123312.mlab.com:23312/soundfactory' }; 

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(部分工作的代码,并不像我原来的server.js文件抛出db.collections错误)

 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,{}); //check below line changed require('./app/routes')(app, database); app.listen(port,() => { console.log("We are live on"+port); }); }) 

       

网上收集的解决方案 "Node js&mongoDB – TypeError:db.collection不是一个函数"