Im trying to connect to mongo db by running mongo server by --auth option. In the below code 'sample' db is dynamic. How can I put a entry for adding username and password for 'sample' db by nodejs.
//Admin user name and password created through mongo shell
var conn = mongoose.createConnection('mongodb://username:password#localhost/admin');
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function callback () {
//Dynamic DB creation
var conn = mongoose.createConnection('mongodb://username:password#localhost/sample');
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function callback () {
console.log('\nDatabase is opened...\n')
});
The above line throws error since 'sample' db is not authenticated. How can I resolve this issue. Thanks in advance.
Related
I am getting the below error when trying to connect using moongoose.
MongooseError: You can not mongoose.connect() multiple times while connected.
throw new _mongoose.Error('You can not mongoose.connect() multiple times while connected.');
^
MongooseError: You can not mongoose.connect() multiple times while connected.
at new MongooseError (/node_modules/mongoose/lib/error/mongooseError.js:10:11)
Please help me find the cause for this and how to prevent it
In mongoose version 5.6.1 the check was added https://github.com/Automattic/mongoose/pull/7905
Revert to an older version for a quick fix.
In order to use multiple MongoDB connections use mongoose.createConnection function instead of mongoose.connect.
mongoose.createConnection Will give you a connection object which you can further use in your model file, Cause models are always bound to a single connection
let config = require('../config');
let mongoose = require('mongoose');
exports.connect = function () {
const db = mongoose.createConnection(config.mongoUrl, {
reconnectInterval: 5000,
reconnectTries: 60
// add more config if you need
});
db.on(`error`, console.error.bind(console, `connection error:`));
db.once(`open`, function () {
// we`re connected!
console.log(`MongoDB connected on " ${config.mongoUrl}`);
});
};
I've had the same problem and solved pretty easily.
All i had to do was to remove any connections in my controllers.
Before:
Server.js
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/DB';
mongoose.connect(connectionString);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
//Server code...
Controller.js
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/DB';
mongoose.connect(connectionString);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
//Controller code...
After:
Server.js
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost:27017/DB';
mongoose.connect(connectionString);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
//Server code...
Controller.js
//Controller code...
Obviously I removed it from all my controller files.
As pointed out by 'iamdimitar', the ability to call mongoose.connect() more than once was removed in this PR. This is said to be done to prevent errors.
If you must call mongoose.connect() more than once, you can use one mongoose.connect() and use mongoose.createConnection() for the rest. That worked for me (I only used one other mongoose.createConnection())
I have started working of late on MEAN technologies;
I have a module myModule. It has routes, services, models accessing database.
I have created another project, myAnotherModule in a separate directory, and have "npm link" ed it into myModule. While I try to use Mongoose in myAnotherModule, it is unable to access DB with proper credentials.
In the following code in myAnotherModule,
var db = mongoose.connection.db;
var mongoDriver = mongoose.mongo;
var gfs = new grid(db, mongoDriver);
it does not find the mongoose.connection.db and db is undefined.
Whereas if I use these lines in myModule, then the code works fine.
Why is myAnotherModule not able to find mongoose.connection.db?
How does npm link work?
Try to connect following way :
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("h");
});
exports.test = function(req,res) {
res.render('test');
};
I happened to encounter this issues recently as well. Typically people separate db config thus cause this problem. Try to declare in proper block that ensures mongodb is already connected.
db.once('open', function callback () {
var gfs = new grid(mongoose.connection.db, mongoDriver);
});
in my app.js, I create a mongodb connection when app starts.
mongoose.connect(config.db, {});
var db = mongoose.connection;
db.on('error', function () {
log.error("Failed to connect to database");
process.exit(1);
});
db.once('open', function () {
log.info("Connected to database");
});
The app.js is used from bin/www.js (with require('./../app')), in which the http server is created.
Currently, if db connection is unsuccessful, app terminates, but http server got created before terminating, since db creation failure is reported asynchronously.
I need to block http server creation until db connection is successful, but I need to keep the server creation code in bin/www.js itself, without moving it to db connection successful callback in app.js.
Is there any way I can do this?
You can launch your server only when the connection is done:
db.once('open', function () {
log.info('Connected to database');
launchMyServer()
});
or if you want to use it in another file :
module.exports = function initConnection(callback) {
mongoose.connect(config.db, {});
var db = mongoose.connection;
db.on('error', function (err) {
log.error('Failed to connect to database');
process.exit(1);
});
db.once('open', function () {
log.info("Connected to database");
callback();
});
};
And from your www.js file:
const initConnection = require('./../app')
initConnection(function () {
launchMyServer()
})
I'm using mongoose, and I need to get stats of database.
I know about YourModel.collection.stats(), but thats just for a collection, I need similar thing, but for the database.
Please dont suggest running the shell command. I want to do it using mongoose.
You can call db.stats on the mongoose.connection object:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
db.db.stats(function(err, stats) {
console.log(stats);
});
});
In addition to MrWhilihog's post, you can also get the data doing the following:
var db = mongoose.connection;
db.db.stats(function (err, stats) {
console.log(stats);
});
This way you are able to get the stats later when your connection is already open.
I am developing a nw.js application and trying to use mongoose - the mongodb vesrion of node.js as database.
I have connected the mongoose as,
var mongoose = require('./mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/myDBName');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
alert();
});
where mongoose folder located at the root folder of my project, but it given the following error.
message: "connect ECONNREFUSED 127.0.0.1:27017"
name: "MongoError"
I also tried with mongoose.connect('mongodb://localhost/myDBName');and for require statement var mongoose = require('mongoose'); but both are of no use. Where i'm missing exactly?