I've been trying to set up a basic MongoDB example on my computer. But I can't get much to work.
When I try to retrieve a collection from my DB (there is only one), I get the error:
TypeError: db.getCollection is not a function
If I try accessing my collection directly by it's name, I get the error
TypeError: Cannot read property 'insert' of undefined
I created my database online on mLab, so I know the collection exists.
This is my server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const db = require('./db');
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, database);
app.listen(port, () => {
console.log('We are live on ' + port );
});
})
And this is my route:
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.getCollection('facts').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};
Why can't I access the getCollection() function?