I have a nodejs app which connects to Mongodb installed locally with the code :
var mongo = require('mongodb');
var nodemailer = require("nodemailer");
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('clients', server, {safe:false});
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'clients' database");
db.collection('clients', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'clients' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findAll = function(req, res) {
db.collection('clients', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Now I want to move this code to Heroku. According to Heroku, my code should look something like :
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
mongo.Db.connect(mongoUri, function (err, db) {
db.collection('mydocs', function(er, collection) {
collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
});
});
});
I can't seem to figure out how to restructure my code for it to work on Heroku.
Does it have to be on heroku?
You could keep your code on Heroku, easily configure a free Mongodb instance/datasource in Mongolab ( https://mongolab.com/products/pricing/ ) and adjust your code to connect to the free Mongodb instance on Mongolab:
mongodb://dbuser:dbpassword#dfs12345.mongolab.com:56789/dbname
Ref: http://docs.mongolab.com/connecting/
Related
I am learning Nodejs, but now I am getting this
error
there is no more code accept this:
let express = require('express')
let mongodb = require('mongodb')
let server = express()
let db
let connectionString = 'mongodb+srv://admin:******#cluster0-1vj27.mongodb.net/TodoApp?retryWrites=true'
mongodb.connect(connectionString, {useNewUrlParser: true}, function(err, client) {
db = client.db("TodoApp")
server.listen(3000)
})
server.use(express.urlencoded({extended: false}))
server.get('/', function(req,res) {
res.send(`....`)
})
server.post('/create-item', function(req, res) {
db.collection('items').insertOne({text: req.body.item}, function() {
res.send("Thank you submitting the form.")
})
})
I am new to node, please help I am stuck.
What should I do now please help
You must use mongodb.MongoClient, not mongodb directly :
const mongodb = require('mongodb');
const mongoClient = mongodb.MongoClient;
// connect
Find an example here : https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
Also, you should check if there is an error before trying to access client :
mongoClient.connect(connectionString, {useNewUrlParser: true}, function(err, client) {
if (err) {
console.error(error);
return;
}
db = client.db("TodoApp")
server.listen(3000)
})
I'm new in node.js and mongo db and i have done my code like this in all my routes.
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var ObjectID = mongo.ObjectID;
var collection;
//Connection to mongo db using mongo client
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {
//connection error or success message
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
throw err;
} else {
console.log("connected to the mongoDB");
}
//index
router.get('/', function(req, res) {
collection = db.collection('category');
collection.find({}).toArray(function(err, category) {
collection = db.collection('subcategory');
collection.find({}).toArray(function(err, subcategory) {
collection = db.collection('product');
collection.find({}).toArray(function(err, product) {
collection = db.collection('banner');
collection.find({status: 'A'}).toArray(function(err, banner) {
console.log(banner);
res.render('home',
{
title : 'Home',
categorys : category,
subcategorys : subcategory,
products : product,
banner : banner
}
);
});
});
});
});
});
});
module.exports = router;
please help me to make a connection in common and access it from all my routes without repeating the connection call. thanks in advance
Here is the draft code to keep the connection outside each request (i.e. connect once) and reuses the database/collection variable.
NodeJS Mongo Driver default connection pool size is 5.
Important: db and categoryCollection variables are kept outside each requests.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MONGODB_URI = 'mongodb://127.0.0.1:27017/mydb';
var db;
var categoryCollection;
// Initialize connection once
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
if(err) throw err;
db = database;
categoryCollection = db.collection('category');
app.listen(3000);
console.log('Listening on port 3000');
});
app.get('/', function(req, res) {
categoryCollection.find({}).toArray(function(err, category) {
});
});
You can use Mongoose to connect to MongoDB. With Mongoose you need to connect to the database only once to access it from all the routes. In you app.js add these lines:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test_db', { useNewUrlParser: true }, function (err) {
if (err) throw err;
});
and in your routes you can now access MongoDB without having to write any connection code.
I'm trying to use MongoDB with Node/Express. I made the official example work:
var express = require('express')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var app = express()
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
insertDocuments(db, function() {
db.close()
})
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
// Some code
], function(err, result) {
// Some code
callback(result)
})
}
app.get('/insert-document', function(req, res) {
// res.send()
})
How can I make it so that Mongo is available inside Express' HTTP methods? For instance, to use insertDocuments() inside app.get('/insert-document', function(req, res)?
EDIT (full server.js file):
var express = require('express')
// var PouchDB = require('pouchdb')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')
var app = express()
var compiler = webpack(config)
// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
var db
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db
})
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents')
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null)
assert.equal(3, result.result.n)
assert.equal(3, result.ops.length)
console.log("Inserted 3 documents into the document collection")
callback(result)
})
}
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
stats: {
colors: true,
chunks: false
}
}))
// enable hot-reload and state-preserving
// compilation error display
app.use(require('webpack-hot-middleware')(compiler))
app.get('/docs', function(req, res) {
// res.send()
insertDocuments(db, function() {
db.close()
})
})
app.listen(8080, 'localhost', function (err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:8080')
})
I get
TypeError: Cannot read property 'collection' of undefined
at insertDocuments (/home/alex/node/project-mongo/build/dev-server.js:24:22)
Refer codes here, save the connection db as one global variable, sample codes as below.
var db;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err)
console.log("Connected correctly to server")
db = db;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get('/insert-document', function(req, res) {
// insertDocuments() could invoked here.
});
I'm trying to insert some data in my mongodb with nodejs whenever a socket is emitted. Here is the code:
io.sockets.on( "connection",function( socket ){
socket.on( "send", function( data ) {
console.log(data.name + " and the content is: " + data.content);
mongodb.connect( "mongodb://127.0.0.1", function( err, db ) {
if(err) throw err;
var to_be_inserted = {name: data.name,content: data.content};
db.collection("chat").insert(to_be_inserted,function(err,objects){
if(err) throw err;
});
})
})
})
However whenever I go to my mongo console and type
db.chat.find()
I cannot find the inserted record. I'm sure that I have mongod open and I'm sure that the socket is emitted. Moreover the consoloe.log before the insertion does work.
Here is my mongo client
var mongodb = require("mongodb").MongoClient;
My console which runs the nodejs server does not log any error.
You should specify a database name (here: myDatabase ) and a port number (for safety).
mongodb.connect("mongodb://127.0.0.1:27017/myDatabase", function( err, db ) {
When searching the record in the mongo shell try:
use myDatabase
db.chat.find()
You forget to include the port number and database of mongodb,
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
}
try this code
var MongoClient=require('mongodb').MongoClient;
var Server=require('mongodb').Server;
var mongoc=new MongoClient(new Server("localhost",27017));
mongoc.open(function(err)
{
db.collection(<collection_name>).insert(<query>,function(err,result)
{
});
const http = require('http');
const hostname = '127.0.0.1';
const port = 8081;
var express = require("express");
var bodyParser = require('body-parser');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
app.use(bodyParser.json());
app.get('/get', function (req, res) {
res.send('Hello World')
})
var data = {
title: 'my title',
content: 'my content'
};
// This responds a POST request for the homepage
app.post('/say/:userid', function (req, res) {
var queryParameter=JSON.stringify(req.query);
res.send('Hello POST'+req.params.userid+""+queryParameter);
})
app.post('/insert', function (req, res) {
console.log(req.body);
res.send('Hello POST'+JSON.stringify(req.body));
/* var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017"; */
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbase = db.db("mydb");
var myobj = { name: JSON.stringify(req.body.name), address:JSON.stringify(req.body.address) };
dbase.collection("student").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
var express = require('express');
var routes = require('./routes');
var socket = require('socket.io');
var fs = require('fs');
var app = module.exports = express.createServer();
var Server = require('mongodb').Server,
Db = require('mongodb').Db,
Connection = require('mongodb').Connection;
var host = 'localhost';
var port = Connection.DEFAULT_PORT;
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:false});
db.open(function(err, db) {
console.log('opened');
app.listen(3000);
});
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
var array = collection.findOne({word:'TEST'}, function(err, item) {});
console.log(array);// <----always "undefined"
});
});
I try to insert the object into the database. And by using "console.log(array)" everytime,I find that it always be "undefined". Is it can't be insert into the database or can't be found from the database. How can I solve it??
But, The 'console.log(item)' shows 'null'. So does it sucessfully insert into the database, or should I change another way to get the object from database.
collection.findOne is asynchronous, so you don't use the return value of the function; instead, you should console.log(item) from inside your (currently empty) callback.
db.collection('locations', function(err, collection) {
var object= {word:'TEST'};
collection.insert(object, {safe:true}, function(err, result) {
collection.findOne({word:'TEST'}, function(err, item) {
console.log(item);
});
});
});