Recommended way to change database in existing connecction with node-mysql - node.js

I am trying to change database in an existing connection in node.
The connection may or may not have database name in createConnection call.
Here's the code:
var mysql = require('mysql');
connection = mysql.createConnection( {
host : 'localhost',
user : 'me',
password : 'secret',
port : 3306,
/* database : 'test' // optional */
});
I am using node-mysql lib.
Currently I'm closing the connection and re-connecting.
Is there any better way to do that? Similar to mysql_select_db in php?

You can change some of the connection parameters* with the changeUser method:
connection.changeUser({database : 'my_database'}, function(err) {
if (err) throw err;
});
*List of these parameters:
user: The name of the new user (defaults to the previous one).
password: The password of the new user (defaults to the previous one).
charset: The new charset (defaults to the previous one).
database: The new database (defaults to the previous one).

The only way I have found is to use the 'USE' command
in your example it would look like this
let database = 'my_database';
connection.query(`USE ${database}`, (error, results, fields) => {
...
});
after that all queries using this connection would be sent to the new database

Or just use database name in query
conn.query('SELECT H FROM other.GeoDB WHERE H = \'r1r0f\' LIMIT 1 ', function (err, res, f)
conn.query('SELECT * FROM data.users WHERE U = \'123\' LIMIT 1 ', function (err, res, f)

Related

Orientdb query approach to get properties of vertices and edges

Im a newbie to orient db .I have a vertex user which has properties adress,name and another vertex Images with properties imagename,date.Both are connected by and edge postedby.Now I want to write a query to select all images posted by a user with all the properties of both the vertices.How can I write the query to get this.I use orientjs in my project
Try this:
var OrientDB = require('orientjs');
var db = OrientDB({
host: 'localhost',
port: 2424,
});
var db = db.use({
name: '<db name>',
username: '<username>',
password: '<pwd>'
});
db.query('select address, name, out("postedby").imagename as imagename, out("postedby").date as date from User where name = "<insert a name>" unwind imagename,date')
.then(function (response) {
console.log(response);
});
db.close();
Hope it helps
Regards

role does not exist and syntax error for inserting query in NodeJs into postgresql

I've created a table with the name of user in postgres which contains id, name, family columns (id is auto-increment). The query which I want to insert into the postgres likes the following:
var config = {
user: 'username',
database: 'databaseName',
password: 'password',
host: 'localhost',
port: 5432,
max: 10,
idleTimeoutMillis: 30000
};
const pool = new postgre.Pool(config);
let query = "INSERT INTO user(name, family) VALUES ('name', 'family')";
pool.query(query, [], function (err, result) {
if (err) {
return console.error("error running query", err);
}
console.log("done!");
});
But, I've got the following error:
Syntax error near user
Also, I have tried different approach to send the request liked the following:
const connectionString = "http://localhost:5432/databaseName?username=username&password=password";
const client = new postgre.Client(connectionString);
client.connect();
const query = client.query("INSERT INTO user(id, name, family) VALUES ('name', 'family')");
query.then(x => { console.log("done!")});
query.catch(x => { console.log(x)});
But I've got the following error:
role \"UserName\" does not exist
Also, the UserName (name of the server) in the body of the error is not the same as the username of the database.
I've checked the all possible fallacies such as the correctness of the username and password.
Therefore, the question is what is the problem?
All of these problems come from the table name. As mentioned in this post, the name of user is a reserved name in postgres. Therefore, these errors will be passed if change the name of the user table such as users.
user is a reserved word in PostgreSQL that refers to the currently logged in user. For that reason, in order to be able to use a table with name user, the name must always be inside double quotes - "user".

Is it necessary to open MongoDB connection every time I want to work with the DB?

In the example I am working with is this code:
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/my_database_name';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// Get the documents collection
var collection = db.collection('users');
//Create some users
var user1 = {name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']};
var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};
// Insert some users
collection.insert([user1, user2, user3], function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
//Close connection
db.close();
});
}
});
As you may see, he is doing an operation in the connect function. I would like to keep it modular and separate the connection from DB operations.
My suggestion would be to make a singleton on db variable and reuse that one. At least that's what I would do in Java to which I am used to.
However, I am not sure as in the example he hasn't suggested anything like that.
I would recommend against maintaining one connection if you want any kind of scalability.
There are a number of options for connection pooling, etc, but most folks who spend any time at all with Node and MongoDB end up moving to Mongoose at some point.
In addition to adding a nice schema layer, it offers connection abstraction so that you can default to a shared connection by calling mongoose.connect(), or you can create multiple connections or participate in connection pooling by calling mongoose.createConnection(). In both cases, you call it without a callback, and the mongoose machinery will defer subsequent calls to the module until after the connection is established, so that your code doesn't have to care.
Something like your use case might look like so:
// in your app.js or server.js file
var mongoose = require('mongoose');
mongoose.connect(config.db.url); // assuming you have some module that handles config variables
Then in ./models/user.js
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
age: Number,
roles: [String]
});
mongoose.model('User',UserSchema);
finally, in lets say a seed function to create your initial batch of users:
const mongoose = require('mongoose'),
User = mongoose.model('User');
// create some users
var user1 = new User({name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']});
var user2 = new User({name: 'modulus user', age: 22, roles: ['user']});
user1.save(console.log);
user2.save(console.log);
I believe maintaining a single connection is the best as mentioned in another thread:
The primary comitter in node-mongodb-native 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 a new connection pool. So open it once an[d] reuse across all requests.
Say on server start initiate the mongo connection.
Server.js:
...
var db = require('./db');//require db.js
db.openMongoConnection(function(error)
{
if(error)
{
console.log(error);
console.log("cannot make the connection with database");
}
else
{
server.listen(7400);//say ur server listening on 7000 port
}
}
db.js
var db1;
var MongoClient = require('mongodb').MongoClient;
exports.openMongoConnection = function(callback)
{
MongoClient.connect(<YourUrl1>,function(err,dbInstance)
{
if(err)
{
callback(err);
}
else
{
db1 = dbInstance;
callback(null);
}
});
};
exports.getCollection = function(collectionName, callback){
dbInstance.collection(collectionName, function(err, collectionInstance){
if(err)
{
callback(err);
}
else
{
callback(null, collectionInstance)
}
});
}
Then you can call the getCollection to use at anytime by requiring dbInsance

Grant user roles in MongoDB via nodejs

I'm trying to write a code in Node.JS that grant roles to users in MongoDB.
I know a way via the CLI:
db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )
How can i do it through Node.JS?
Thanks
I don't know that it's the only way, but the only thing I can see in the docs is to grant a role when you add a user.
var MongoClient = require('mongodb').MongoClient,
test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
// Use the admin database for the operation
var adminDb = db.admin();
// Add the new user to the admin database
adminDb.addUser('admin11', 'admin11', {roles : ['blah']}, function(err, result) {
// Authenticate using the newly added user
adminDb.authenticate('admin11', 'admin11', function(err, result) {
test.ok(result);
adminDb.removeUser('admin11', function(err, result) {
test.ok(result);
db.close();
});
});
});
});
Yes, it's confusing, the mongo driver only seems to implement the addUser and removeUser functions. Nevertheless, you can use the 'command' function of the mongo driver to access the functions available in the mongo shell. This works for me on mongo 3.4:
...
const db = client.db('admin').admin();
const theRoles = [{role:'readWrite', db: 'someDB'}]
await db.command({grantRolesToUser: 'theUsername', roles: theRoles});
...
The documentation of the command function is rather opaque, and I had to use trial and error to find the proper syntax.

Mongoose migrate

Anyone got a migrate module that they use to migrate mongodb data with the mongoose plugin?
I am currently using the 'migrate' module and it works great except for the fact that I need to create/destroy my connection in each up/down.
I.E.
// Setup mongoose
var mongoose = require('mongoose')
, Role = require('../models/role')
, User = require('../models/user');
exports.up = function(next) {
// get a brand new connection for this patch.
mongoose.connect('mongodb://localhost/sagedb');
var adminUser = {
username: 'admin',
password: 'admin'
};
User.createUser(adminUser, function(err, user) {
if (err) {
mongoose.disconnect(); // Make sure to close connection
return next(err);
}
mongoose.disconnect(next); // Make sure to close connection
});
};
exports.down = function(next) {
mongoose.connect('mongodb://localhost/sagedb'); // new connection for down
User.getUserByUsername('admin', function(err, user) {
if (err) {
mongoose.disconnect(function() { // make sure to close connection
return next(err);
});
}
if (!user) {
mongoose.disconnect(); // make sure to close connection
return next();
}
User.deleteUser(user, function(err, user) {
console.log('deleted user');
mongoose.disconnect(next); // make sure to close connection
});
});
};
Probably a much better way to do this. Wondering if the only option is to create my own module that starts the connection once and closes it when all patches are complete.
I have seen mongoose-migrate which tracks migration in database collection. Not really specific to mongoose IMHO, I would rather still use the .migrate file but only have to open the connection once.
The reason of the issue is that you have connection "connected" each time, on every ,migration
That is why you have to disconnect.
The same situation if you replace connect with mongoose.createConnection. you will need to close it.
How to solve?
move
var mongoose = require('mongoose')
, Role = require('../models/role')
, User = require('../models/user');
into module like db
var mongoose = require('mongoose')
, Role = require('../models/role')
, User = require('../models/user');
module.exports = mongoose
and just require it
var mongoose = require('./db')
So you will have:
Single connection
All models loaded in one place
Clean code in
migrations
You can also try my migrate-mongoose migration framework which provides the mongoose connection right out of the box.
in your up or down function you can just access your models like this
this('user').findOne({ name: 'Sergey' });
It also persists your migrations to the database instead of the file system.
You also have east migration framework that is very powerful and it also has mongoDB adaptors:
https://github.com/okv/east
Then you will crate migration with command:
east create my_migration_name
And then your migration scripts will look like this:
exports.migrate = function(client, done) {
var db = client.db;
db.........
done();
};
exports.rollback = function(client, done) {
var db = client.db;
db.........
done();
};

Resources