I am trying to post data to database that I have created on mLab and I am getting this error but I don't know whats going wrong.I also have read previously asked question on this topic but I am not able to solve my error as I am new to this. So here I am posting the code which I am trying to implement and It is taken from this tutorial 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:[email protected]: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]);
}
});
});
};
So I voted for the answer which said to just go down to mongodb 2.2.33 because I tried it and it worked, but then I felt weird about just downgrading to fix a problem so I found the solution which allows you to keep version >= 3.0. If anyone finds this issue and their problem wasn't passing in a blank reference like the accepted answer, try this solution out.
When you run..
MongoClient.connect(db.url,(err,database) =>{ }
In mongodb version >= 3.0, That database
variable is actually the parent object of the object you are trying to access with database.collection('whatever')
. To access the correct object, you need to reference your database name, for me that was by doing
MongoClient.connect(db.url,(err,database) =>{
const myAwesomeDB = database.db('myDatabaseNameAsAString')
myAwesomeDB.collection('theCollectionIwantToAccess')
}
This fixed my errors when running my node.js server, hopefully this helps somebody who doesn't just want to downgrade their version.
(also, if you don't know your db name for some reason, just do a console.log(database) and you'll see it as an object attribute)
EDIT (June 2018):
According to this, the callback actually returns the connected client of the database, instead of the database itself.
Therefore, to get the database instance, we need to use this method, which takes in a dbName
. In the documentation it said If not provided, use database name from connection string.
, as mentioned by @divillysausages in the comments below.
In short, we should call database.db().collection('theCollectionIwantToAccess');
if the dbName is provided by url, where the database
is actually client
for better understanding
The error is in the mongodb library. Try to install version 2.2.33
of mongodb
. Delete your node_modules
directory and add
"dependencies": {
"mongodb": "^2.2.33"
}
Then
npm install
and there you are
MongoClient.connect(uristring, function (err, database) {
var db=database.db('chatroomApp');
var collections=db.collection('chats');
});
Need to Get the Database first before trying to access the collections.
According to the mongo document, we need to change the connection as bellow,
The legacy operation
MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
// Database returned
});
is replaced with
MongoClient.connect('mongodb://localhost:27017/test', (err, client) => {
// Client returned
var db = client.db('test');
});
Don't need to downgrade the mongo version :)
Uninstalling existing mongodb package and reinstalling using the following commands resolved the issues for me. :)
npm uninstall mongodb --save
npm install [email protected] --save
PS: Thanks to @MihirBhende and @yaxartes
FYI,
Prefer non-rc releases from https://github.com/mongodb/node-mongodb-native/releases, if you are new to the field.
In your server.js, you are passing empty object where you need to pass database as second argument as its what your routes/index.js export function expects.
PFB updated 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);
});
});
I ran into the same issue. It looks like the mongodb driver module for node was updated since the video was created. I found the code below in the docs which works.
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/<dbName>';
MongoClient.connect(url, (err, db) => {
db.collection('<collection-name>').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc);
});
// Close the DB
db.close();
});
});
is replaced with
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017'; // remove the db name.
MongoClient.connect(url, (err, client) => {
var db = client.db(dbName);
db.collection('<collection-name>').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc);
});
// Close the DB
client.close();
});
});
Here is a link to the latest docs in case we run into further syntax issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With