I am new to Bookshelf JS and wanted to do a like query with the database. I read the documentation on their official website , but I am unable to figure this out.
The following is my code:
1. var DB = Bookshelf.initialize({
client: 'mysql',
connection: config
});
2. var User1=DB.Model.extend({
tableName: 'applicationPrimary',
});
3. Now I want to make a query like:
select * from applicationPrimary where id like '%2%' ;
4.I have tried the following:
Model.User1.query(function(qb) {
qb.where('id', 'LIKE', '%2%')
}).fetch()
.then(function(model) {
console.log(model)
});
The following is the manner I am initialising and setting up:
1. var Bookshelf = require('bookshelf');
var config = {
host: 'localhost',
user: 'root',
password: 'root',
database: 'mydb',
charset: 'UTF8_GENERAL_CI'
};
var DB = Bookshelf.initialize({
client: 'mysql',
connection: config
});
module.exports.DB = DB;
2. var DB = require('./db').DB;
var User1 = DB.Model.extend({
tableName: 'applicationPrimary',
});
module.exports = {
User1: User1,
};
and then I am using it as:
var Model = require('./model');
in the file I am using User1.
The above doesn't work and it throws an error saying there is no function called query.
Any help is highly appreciated.
Your syntax for the LIKE is right, the problem is you should use .where on the User1 object, not .query on Model.User1
User1.where('id', 'LIKE', '%2%').fetch().then(...)
Related
I'm using the mysqldump library, and mysql-import. I need to do a restore of my MySQL database, but at the time of doing it, it tells me that you cannot add duplicate files, therefore I manually put DROP TABLE IF EXIST, and it worked and overwritten the database, according to In the Mysqldump documentation there is a way to add the DROP TABLE by default, but I really don't know how to do it, can someone help me?
var mysqldump = require('mysqldump');
const controller = {};
controller.backupDatabase = function(req, res, next) {
if(mysqldump){
mysqldump({
connection: {
host: 'localhost',
user: 'root',
password: '',
database: 'decoracionesalves',
},
dumpToFile: './DecoracionesAlves.sql',
});
}else{
//Hacer algo aqui.
}
};
module.exports = controller;
You can set dropIfExists to true on the schema dump table option.
mysqldump({
connection: {
host: 'localhost',
user: 'root',
password: '',
database: 'decoracionesalves',
},
dump: { schema: { table: { dropIfExist: true } } },
dumpToFile: './DecoracionesAlves.sql',
});
See API docs for SchemaDumpOptions
I'm developing an application with node.js and in login form I ask user to select the database but I don't know how to set the connection with the selected database.
How can I put several connections in my config.js?
And how can I set a connection wit a selected database?
var mssql = require("mssql");
var config =
{
user: "user",
password: "password",
server: "IP",
database: "db_name"
}
var db = new mssql.Connection(config);
db.connect(function(err)
{
console.log(err);
});
module.exports = db;
Thank you
To do this, you can just make two database connections
var mssql = require("mssql");
var config =
{
user: "user",
password: "password",
server: "IP",
database: "db_name"
}
var db = new mssql.Connection(config);
var db2 = new mssql.Connection(config);
db.connect(function(err)
{
console.log(err);
});
db2.connect(function(err)
{
console.log(err);
});
module.exports = {db: db, db2: db2};
If you need a separate config, you can just make two configs. To use the first db, just require("config").db and the second db is at require("config").db2
When I run the server attempting to create two databases (db1 and db2), the system kicks backs this error:
Possibly unhandled SequelizeBaseError: database "db2" does not exist
As a reference, there is similar stackoverflow question on this topic here, however, the author of the solution does not cover the solution to how the server.js file is setup. You will notice I have structured my index.js file similar to their answer.
My models/index.js file and server run and executes scripts properly, yet the second database does not work at all and does not even get initialized.
Can someone provide a solution for the server.js file to accurately initialize two databases in this one server?
The following is the partial code from the models/index.js and server.js files. In the server.js file, I am using .sync to initialize the databases.
server.js
[...]
//sync's sequelize DB and tables
db['db1'].sequelize.sync(function(err){});
db['db2'].sequelize.sync(function(err){});
models/index.js
var databasesArray = ['db1', 'db2']
var databasesObj = {
database: {
db1: {
DBName: 'db1',
User: user,
Password: password,
Config: config,
},
db2: {
DBName: 'db2',
User: user,
Password: password,
Config: config,
}
}
} // EOF databaseObj
for(var i = 0; i < databasesArray.length; ++i) {
var databasePointerToOBJ = databasesArray[i];
var database = databasesObj.database[databasePointerToOBJ]
if(database.DBName == 'db1'){
var sq = new Sequelize(database.DBName, user, password, config)
db['db1'] = {
Sequelize: Sequelize,
sequelize: sq,
Table1: sq.import(__dirname + '/...')
}
}else if(database.DBName == 'db2'){
var sq = new Sequelize(database.DBName, user, password, config)
db['db2'] = {
Sequelize: Sequelize,
sequelize: sq,
Table1: sq.import(__dirname + '/...')
}
}
}
module.exports = db;
--- EDIT ---
The author of the solution was correct. In order for a new database to be created, it must be created prior to being sync'd. As piotrbienias rightly notes, adding the code for adding a new DB in a your initialization script would be the best option. Piotrbienias solution is .js option. The code that worked for me is a .sh option and is as following:
PG_HOST=localhost
PG_PORT=5432
PG_DB=databaseName
PG_USER=ubuntu
PG_PASS='EnterPassword'
sudo -u postgres createdb -U postgres -O $PG_USER $PG_DB
You need to create the database manually before trying to access it via Sequelize - it does not create it if it does not exists. You can use a pg module inside some initialisation script to create the DB via CREATE DATABASE before doing any synchronisation and connection, or simply create it via postgres CLI
const pg = require('pg');
module.exports = function(next){
var connectionData = {
user: 'postgres',
password: 'password',
host: 'localhost'
};
var databaseName = 'db2';
var connectionUri = `postgres://${user}:${password}#${host}/postgres`;
pg.connect(connectionUri, function(err, client, done) {
client.query(`CREATE DATABASE ${databaseName}`, function(error){
// here you can perform some sequelize operations after creating the database
client.end(); // disconnect client
next(); // you can call it with some parameter like Sequelize instance etc.
});
});
};
I am currently developing a node.js backend for a mobile app with potentially many users. However it's my first time in developing node.js. I was following a tutorial on how to connect to a mysql database via mysql pools.
I am able to create a single mysql connection and do queries via my routes.
The problem arises once I establish the file structure mentioned in the tutorial:
dbConnect
-[models]
--users.js
-db.js
-server-ks
I am not getting an error message regarding the connection of the mysql database - even if I enter a wrong password.
// server.js
///////////////////////////// basic setup ///////////////////////////////////
var restify = require('restify');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var db = require('./db');
var users = require('./models/users');
///////////////////////////// initilisation of the server ///////////////////////////////////
var server = restify.createServer({
name: 'testUsers',
});
server.use(restify.bodyParser({ mapParams: true }));
///////////////////////////// Säuberung der URL //////////////////////////////////////////
server.pre(restify.pre.sanitizePath());
///////////////////////////// MySQL Instanz starten //////////////////////////////////////////
db.connect(db.MODE_PRODUCTION, function (err) {
if (err) {
console.log('Unable to connect to MySQL.')
process.exit(1)
} else {
server.listen(8080, function () {
console.log('Listening on port 8080 ...')
})
}
})
///////////////////////////// implementation of the routes ///////////////////////////////////
function send(req, res, next) {
var test = users.getAll();
res.json({ test: 'Hello ' + req.params.name });
return next();
};
My DB.js file looks the following:
var mysql = require('mysql'),
sync = require('async')
var PRODUCTION_DB = 'userDB',
TEST_DB = 'userDB'
exports.MODE_TEST = 'mode_test'
exports.MODE_PRODUCTION = 'mode_production'
var state = {
pool: null,
mode: null,
}
exports.connect = function (mode, done) {
state.pool = mysql.createPool({
connectionLimit: 50,
host: 'localhost',
user: 'user',
password: 'password',
database: 'userDB' // test
//mode === exports.MODE_PRODUCTION ? PRODUCTION_DB : TEST_DB
})
state.mode = mode
done()
}
exports.get = function () {
return state.pool
}
Could it be, that the tutorial spared out an essential part in utilizing mysql pools and node.js?
Thanks in advance for at least trying to answer that question.
Are there better methods sequelize(?) available to create performant connections to a MySQL database?
It looks like creating the pool object does not actually connect to the database. A big clue is that the createPool function is not asynchronous, which is what you would expect if it was actually connecting at that moment.
You have to make use of the returned pool object to perform a query, which IS asynchronous.
From the documentation:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
I am new to node.js (and mysql in combination with that) and trying to update my database based on request parameter and a request body. My beginning of the file looks like this:
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'm3ttulat0r',
debug: true
});
var app = express();
app.use(bodyParser.json());
My request looks like this:
http://localhost:8080/mettmeister/1
The request body looks like this:
{
"mettmeister": "Jonas"
}
The connection to the database is successful. Then I have the following code:
app.post('/mettmeister/:mettwochId', function(req, res) {
var mettmeister = req.body.mettmeister;
var mettwochId = req.params.mettwochId;
var query = 'UPDATE mettwoch SET mettmeister = "'+ mettmeister +'" WHERE mettwoch_id = "'+ mettwochId +'"';
console.log(mettmeister, mettwochId);
connection.query(query, function(err, result) {
if (!err) {
res.status(201);
} else {
res.status(500);
}
});
});
console.log(mettmeister, mettwochId); returns Jonas 1 which is fine.
The problem is that it sends the request and the server gets the message according to the log but nothing happens. The server "stops" at executing the query apparently.
I have debugging turned on and the query looks fine.
--> ComQueryPacket
{ command: 3,
sql: 'UPDATE mettwoch SET mettmeister = "Jonas" WHERE mettwoch_id = "1"' }
If I execute the query manually in my database, it works.. I am really happy for any help. Thank you! :)
Use update query like this
connection.query('UPDATE mettwoch SET ? WHERE ?', [{ mettmeister: mettmeister }, { mettwoch_id: mettwochId }])
Well, I am stupid. Sorry guys :(
I did the following
res.status(201);
Actually you have to finish the request like this:
res.status(201).end();