I'm new at NodeJS and today started MongoDb section. I watch NodeJS videos (which recorded in 2016) , they connecting with mongoose. But it is not working correctly on me.
Codes :
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var mongoDB = "mongodb://localhost/nodedb";
mongoose.connect(mongoDB,{ useNewUrlParser: true } ,function(err,err){
if(err){
console.log("Cant connect");
}else{
console.log("Connected to :" + mongoDB);
}
})
With this method I can connect. At least apperaing in Console :
Connected to :mongodb://localhost/nodedb
But there are some errors and one of them is :
Unhandled rejection MongoError: port must be specified
I write mongodb://localhost:27017/nodedb . But now couldn't connect. Where are issue?
You need to specify mongodb port, default one is 27017
https://docs.mongodb.com/manual/reference/default-mongodb-port/
I use mongoose like this:
mongoose.connect('mongodb://localhost:27017/somename')
.then((db)=>{console.log(`connected`);})
.catch(error=>console.log(error));
Related
I'm testing mongoDB connection in node.js with mongoose. I follow the official guide of mongoose and when I try to connect like they said, mongoose always says I'm connected even if the URI given is fake or wrong. Is my connection trying correct ?
I want to connect my app to a database called 'technicaltest'.
My code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/technicaltest', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
The console ouput:
> set PORT=3001 && node bin/www
Connected to mongoDB !
Same output for this code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/someWeirdyThingsHere', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
I think if mongoose cannot connect to the right database in mongoDB nothing will be prompted in the console...
But here...
The 'connected' event is call anyway.
I think you forgot to add the port(27017) to your mongodb connection.
It should be
const db = mongoose.createConnection('mongodb://localhost:27017/technicaltest', {useNewUrlParser: true});
I have a locally hosted mongodb that I can connect to using mongodb.MongoClient.
Working code:
var mongoClient = require("mongodb").MongoClient;
...
var startApp = function(db) {
// Get our collections in an easy to use format
var database = {
chats: db.collection('chats'),
messages: db.collection('messages')
};
// Configure our routes
require('./app/routes')(app, database);
// START APP
// Start app on port
app.listen(port);
// Tell user the app is running
console.log("App running on port " + port);
// Expose app
exports = module.exports = app;
}
// DATABASE
var database = null;
mongoClient.connect(config.url, function(err, returnDB) {
if(err) {
console.log(err);
} else {
console.log("DB connected");
startApp(returnDB);
}
});
Legacy code that no longer works:
var mongoose = require('mongoose');
...
// Connect to DB
console.log('Connect to database (' + db.url + ')');
mongoose.connect(db.url);
I have added a callback to this connect method but it never gets called (error or no error, this connect function never gets to my callback).
This entire legacy app relies on the API using mongoose to talk to the database so I do not want to redo it all using mongodb. How can I fix this?
*config.url and db.url are loaded from the same file and it is a valid and running mongodb.
It was really easy to fix. Thanks #Bhavik for asking me what version I was using.
I updated mongoose to 4.8.1 by specifying the newest version in packages.json and the issue is resolved.
I'm trying to connect to MongoDB using Mongoose on an Amazon EC2 Linux server.
Here's my code:
var mongoose = require('mongoose');
console.log("Attempting antyhing to do with mongoose"); //shown
var db = mongoose.connection;
db.on('error',console.error.bind(console,'db connection error:')); //not shown
db.once('open',function(){
console.log("Successful connection to db!"); //not shown
});
mongoose.connect('mongodb://localhost:27017/local',function(err){
console.log("some kinda connection made"); //not shown
if(err)
{
console.log("err: "+err);
}
});
Frustratingly, I'm not getting any errors from mongoose whatsoever, but nothing seems to show up.
There seem to be a lot of questions about no callback with mongoose and mongo.
Here's a couple that I've looked at that I don't think are the problem for me:
Listen for the callback quickly:
Mongoose Connection I
moved my db.on('open'... call to before my connect call in case of a
race condition.
Is Mongo running?
Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
Yes, and on port 27017
Also for reference I'm following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
One thing I am doing that I'm worried about is I've split my code up into multiple files. So this mongoose connection code is being called from a app/models/host.js (or bear.js in tutorial) file. Let me know if posting the other files would be helpful.
I also faced the same issue.
Check that the Mongoose version you are using supports the MongoDb server version
Check compatibility on this link: http://mongoosejs.com/docs/compatibility.html
Change the version of Mongoose in package.json file accordingly.
Hope this helps!
Haven't really solved the problem but I found a work-around... not using mongoose. Would still appreciate connecting to mongoose, especially as I was trying to follow a tutorial.
Here's my code that successfully connects to mongodb:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = "mongodb://localhost:27017/host";
//Go Ahead and connect & sketchily initialize the db
var db;
var collection;
MongoClient.connect(url,function(err,database){
if(err){
console.log("Coudln't connect to mongo. Error"+err);
} else{
db = database;
collection = db.collection('hosts');
console.log("Connected to mongo, db good to go");
}
});
I am new to mongoDB and I'm currently working on setting it up with Node express server. I wonder how to manage concurrent requests to the mongodb to read the collection data using the mongoose driver module.
For example:
If 100 users are accessing my server at a time (http://xxxxxx.com/showusers), how will the mongodb connection in the express server work? Will it be a single connection or split into 100 connections, one for each request?
How can I close the connection object in mongodb efficiently after the operation? Or can we leave the connection in the express server as in the below code?
Here follows my code..
Server.js
var express = require('express');
var app = express();
app.set('port', config.port);
app.get('/users',storeusersapi.showUsers);
app.get('/storeUser',storeusersapi._insertUserDetails);
app.get('/findUser/:email',storeusersapi._findUser);
app.listen(app.get('port'),function(){
log.info('Express app started on port ' + app.get('port'));
});
storeusersapi.js
var mongoose = require('mongoose');
var log = require('../config/logger');
// Mongoose connection to MongoDB (ted/ted is readonly)
mongoose.connect('mongodb://localhost/mydb', function (error) {
if (error) {
log.error("MongoDB Connection failure - " +error);
}else{
log.info('MongoDB is connected Successfully!!!');
}
});
// Mongoose Schema definition
var Schema = mongoose.Schema;
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: String
});
// Mongoose Model definition
var User = mongoose.model('users', UserSchema);
exports.showUsers = function(req,res){
User.find({}, function (err, docs) {
res.json(docs);
});
};
exports._insertUserDetails = function(req,res){
var object = new User({first_name:'bob',last_name:'sel',email:'sel#xxxxx.com'});
object.save(function (err) {
if (err) {
log.error('Insertion error - '+ err);
}
else {
log.info("User Stored into database!!!");
}
});
};
exports._findUser = function(req,res){
User.find({ email: req.params.email }, function (err, docs) {
res.json(docs);
});
};
I have answered for both of your question separately.
1. How will the mongodb connection in the express server work?
Once a connection is created to the mongodb database.(using mongoose or any other framework) It will create a pool of connections with that. (Mongoose default pool size is 5, 100 in python) The created connection pool is maintained by the driver therefore those connections can be re-used when connections to the database are required.
The best practice is to create a new connection only once for the whole application. Once connection is created the connection object will be used as a singleton. When you connect to the database using mongoose models, separate connections are allocated from the created connection pool.
If you are going to create a new connection each time then It will cause to a connection churn.
2. How can I close the connection object in mongodb efficiently after the operation ?
I am not sure 100% about this answer. My suggestion is to disconnect the connection when the express application exits.
var db = mongoose.connect('mongodb://localhost:27017/database');
db.disconnect();
According to my knowledge what you have don in the code is correct. You have created a new connection only once. Since the connection pool is created with that you don't need to create more connections.
Please go through this link to get a clear understanding on connection pools and their usage.
https://dzone.com/articles/deep-dive-connection-pooling
Tracing the documentation here and failing to load bson apparently. After running npm start I receive:
Snippet:
var mongo = require("mongodb").MongoClient;
//connect to db server
mongo.connect("mongodb://localhost:28017/myDb", function(err, db){
if(!err) {
console.log("Connected to Database")
}
else{
console.log("failed to connect");
}
});
I have tried updating/reinstalling the driver modules as well. Totally new to the framework & db and this type of error feels so trivial that it is discouraging that I am unable to figure it out. Help!
The default port for mongodb is 27017 (and then 28017 is for a web status page).
http://docs.mongodb.org/manual/reference/default-mongodb-port/
Try this connect string:
"mongodb://localhost:27017/myDb"