Reputation: 1257
I am new beginner in Node.js and MongoDB and started to implement few POST API. I am using MongoDB to insert data via POST, While testing on terminal its showing that database is created, but while doing POST, showing error that db is not found. I am not sure what I am doing wrong. Below is my code
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
var url = "mongodb://localhost:27017/mydb"
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.listen(port, () => {
console.log('We are live on ' + port);
});
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
app.post('/api/notes', function(req, res) {
var myobj = { text: req.body.body, title: req.body.title };
var dbase = db.db("mydb");
dbase.collection('notes').insertOne(myobj, function(err, result) {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
Upvotes: 0
Views: 2184
Reputation: 6242
Your db
is not available outside that's why you are getting the error.
Try this way:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
global.db=db;
//don't close connection here if you want to use outside just put it as global
});
You can refer https://groups.google.com/forum/#!msg/node-mongodb-native/mSGnnuG8C1o/Hiaqvdu1bWoJ for better understanding about MongoDB native connection
Which says:
You open do
MongoClient.connect
once when your app boots up and reuse the db object.It's not a singleton connection pool each
.connect creates anew connection pool
.
Upvotes: 3
Reputation: 557
You just need to understand the variable scopes here. the scope of variable db
is local which means it is not accessible outside the callback of MongoClient.connect
. dbase
will be undefined
if am not wrong.
Try this:
app.post('/api/notes', function(req, res) {
var myobj = { text: req.body.body, title: req.body.title };
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
res.status(500).send('Db Connection Failed..')
} else {
var myobj = { text: req.body.body, title: req.body.title };
var dbase = db.db("mydb");
dbase.collection('notes').insertOne(myobj, function(err, result) {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
})
}
});
});
Upvotes: 1