Using authenticationDatabase option while connecting to mongodb from nodejs - node.js

When I connect to mongodb from shell using mongo I need to use the following
mongo -u xxxx -p xxxx --authenticationDatabase admin then I get full access... but I cannot find a way to specify the authenticationDatabase while connecting from nodejs this is my code
var MongoCli = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/contactapp";
MongoCli.connect(url,function(err,db){
if(err)
{
console.log('Unable to connect');
}
else
{
console.log('Connected at ',url);
db.authenticate('username','password','--authenticationDatabase admin',function(err,res){
if(err)
{
console.log('Error');
}
else
{
console.log('Auth Success');
var collection = db.collection('contact');
collection.find().toArray(function(err,res){
if(err)
{
console.log(err);
}
else if(res.length)
{
console.log('Found ',res);
}
else
{
console.log('No data found');
}
db.close();
});
}
});
}
});
I need to use the authenticationDatabase. Thanks in advance.

Try to change this:
db.authenticate('username','password','--authenticationDatabase admin',function(err,res){
Whit this:
db.admin().authenticate('username', 'password', function(err,res){

I had the same question on using authenticationDatabase with nodeJS, mongodb and mongoose. Passing the whole path with credentials and a flag worked for me
mongodb://username:password#127.0.0.1:27017/databaseName?authSource=admin
authSource is a flag for authenticationDatabase

Related

sqlite3 create database with callback using Node

I've searched on how to create a sqlite3 database with a callback in Node.js and have not been able to find any links. Can someone point me towards documentation or provide a 2-3 line code sample to achieve the following:
Create a sqlite3 database and catch an error if the creation fails for any reason.
Here is what I've tried:
let dbCreate = new sqlite3.Database("./user1.db", sqlite3.OPEN_CREATE, function(err){
if(!err){
logger.infoLog("Successfully created DB file: " + dbFileForUser + " for user: " + username );
} else {
logger.infoLog("Failed to create DB file: " + dbFileForUser + ". Error: " + err );
}
});
dbHandler[username] = dbCreate;
When I execute this, I get the following error:
"Failed to create DB file: ./database/user1.db. Error: Error: SQLITE_MISUSE: bad parameter or other API misuse"
This call without callback works just fine.
var customDB = new sqlite3.Database("./custom.db", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
But in this, I will not know if I run into any errors while creating the Database.
Try this:
let userDB = new sqlite3.Database("./user1.db",
sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
(err) => {
// do your thing
});
Example.
#Irvin is correct, we can have a look at http://www.sqlitetutorial.net/sqlite-nodejs/connect/ and
check it says if you skip the 2nd parameter, it takes default value as sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
and in this case if database does not exist new database will be created with connection.
sqlite3.OPEN_READWRITE: It is to open database connection and perform read and write operation.
sqlite3.OPEN_CREATE : It is to create database (if it does not exist) and open connection.
So here is the first way where you have to skip the 2nd parameter and close the problem without an extra effort.
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.|');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
And this is the 2nd way to connect with database (already answered by #Irvin).
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});

MongoError : selector must be a valid JavaScript object

I am using mongodb driver for nodejs.
I am getting below error while updating a record.
{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}
Here is my script :
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();
});
});
I can write the below line in mongo console & it works.
db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})
You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated)
// collName need not pass in the update function.
Need to use
db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.

How to programatically enable sharding for a database and then shard the collection using node.js mongodb driver?

I have the following nodejs script that currently creates a few trial databases and then creates a collection and inserts a sample entry into the collections. Now I would like to enable sharding for the database and then shard the collection based on the hashed id field. How can I do that?
The host and port in the code point to where mongos is running.
var mongoClient = require('mongodb').MongoClient;
var name = "sampledb";
function start() {
for (var i=4;i<20;++i) {
var dbname = name + i;
mongoClient.connect("mongodb://" + host + ":" + port + "/" + dbname, function(err, db) {
if(err) {
console.log("Error connecting to db");
process.exit(0);
}
db.createCollection("messages", function(err_, result_) {
if (err_) {
console.log("Error while creating collection");
process.exit(0);
}
db.collection("messages").insert({"id":"<random id>"}, {w:0}, function(err, result) {
if(err) {
console.log("Could not insert document");
} else {
console.log("Successfully inserted document");
}
});
//now shard the collections created
});
});
}
}
start();
I could not get hold of proper documentation for my question, can someone please help me out...Thanks.

CouchDb unhandled 'error' event - Node js

I'm new to Node and CouchDb and I'm trying to get my hands on it.
I'm struggling to make a piece of code to work.
I would like to create a table users, insert a new user and 'at the same time' getting another user.
I'm getting this error when starting up node app.js :
antoine#ubuntu:~/projects/couchDb$ node app.js
Database users exists.
{"error":"conflict","reason":"Document update conflict."}
Leaving saveDoc
events.js:48
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1107:15)
at Socket.onend (http.js:1188:27)
at TCP.onread (net.js:369:26)
And here is my very code, is there something wrong?
(When I remove the getDoc function the error goes away)
I'm using couchDB 1.0.1 and node 0.6.12
The jdoe4 and jdoe documents are already present in the users database.
var dbHost = "127.0.0.1";
var dbPort = 5984;
var dbName = 'users';
var couchdb = require('felix-couchdb');
var client = couchdb.createClient(dbPort, dbHost);
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
var db = client.db(dbName);
db.exists(function(err, exists) {
if (!exists) {
db.create();
console.log('Database ' + dbName + ' created.');
} else {
console.log('Database ' + dbName + ' exists.');
}
db.saveDoc('jdoe4', user, function(err, doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.getDoc('jdoe', function(err,doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
It seems to be a library problem => Github Issue Socket Hangout
Look here if you dont know which library fit more your needs.
I quickly realized that felix-couchdb is not compatible with node 8 (I know you're not using version 8, but you will someday), so I switched to nano couchdb and here's the following code:
It will check if the db is created
It will insert only if the key given is unique
It will get the user with a key
var couchdb = require('nano')('http://localhost:5984')
, dbName = 'users'
, db = couchdb.use(dbName)
;
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
couchdb.db.create(dbName, function(err, db_body) {
db.insert(user, 'jdoe4', function(err, doc, header) {
if( err) {
console.log('Cannot save user');
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.get('jdoe', function(err, doc) {
if( err) {
console.log('Cannot get user');
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
One thing worth noting is that, while this will get them at the "same time," it's still making 3 requests to the db, 1 to check if it exists, 1 to insert (or not), 1 to get.

How do I cleanly shutdown mongodb from node.js?

I am running mongodb as a child process from node.js and require to shut down and restart on demand. using Child_Process.kill("SIGINT") would appear to be the correct way but but it leaves mongo in a confused state which won't restart until repaired (or the lockfile is deleted) Is there a better way to do this?
Thanks,
Andy
Doing kill("SIGINT") cause the database to shut down without going through the required steps and could lead to corrupt data files. So i would not recommend do this.
Normal way to stop database is send command { "shutdown" : 1 } or db.shutdownServer() from mongodb shell, but I don't know exactly how to do it from node.js driver.
you can try something like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/admin", function(err, db) {
if (err) {
console.log('mongodb is not running');
process.exit(0);
}
else {
db.command({
shutdown : 1
}, function(err, result) {
console.log('shutting down mongodb - ', err.message);
process.exit(0);
});
}
});
you could end a mongodb process using nodeJS on mac
1) save the script below to a script.js
'use strict'
const exec = require('child_process').execSync;
function killport(port) {
var processId = null
try {
processId = exec(`lsof -t -i:${port}`);
} catch (e) {
console.log("could not catch");
}
if (processId !== null) { // if exists kill
try{
if(exec(`kill ${processId}`)){
console.log("closed");
}
} catch(e){
console.log("error executing");
}
}
}
killport(27017);
2) run node script.js

Resources