我正在尝试将数据从POSTMAN发布到我在mLab上创建的外部数据库但是我收到错误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);
});
})
答案 0 :(得分:4)
删除node_modules文件夹并更改package.json
"mongodb": "^2.2.33"
并运行以下代码:
npm install
答案 1 :(得分:-1)
更改为此require('mongodb').MongoClient;