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 o
I've simple solution:
note_routes.js
db.collection('notes').insert(note, (err, result) => {
replace
db.db().collection('notes').insert(note, (err, result) => {
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.
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.
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err)
//require('./app/routes')(app,{});
//try this
require('./app/routes')(app,database);
app.listen(port,() => {
console.log("We are live on"+port);
});
})
here you have to include the database in the empty {}.
or
you can also try installing mongodb to latest which will solve the issue.
npm install mongodb@2.2.33 --save
else npm install add dependency of "mongodb": "^2.2.33" in node modules.
Dont use database name in connection url:
const mongo_url = 'mongodb://localhost:27017'
Instead use below method:
MongoClient.connect(mongo_url , { useNewUrlParser: true }, (err, client) => {
if (err) return console.log(err)
const db = client.db('student')
const collection = db.collection('test_student');
console.log(req.body);
collection.insertOne(req.body,(err,result)=>{
if(err){
res.json(err);
}
res.json(result);
});
});