waterline and mysql without sails - node.js

I am building a node app and want to use waterline and mysql without sails. I cannot get the adapter to work. The exact error I get with the code from below is:
C:\node\mlb\node_modules\waterline\lib\waterline\core\index.js:70
var schemaAttributes = this.waterline.schema[this.identity].attributes;
TypeError: Cannot read property 'undefined' of undefined
Here is my code:
var Waterline = require('waterline');
var mysql = require('sails-mysql');
mysql.config = {
host: 'localhost',
database: 'mlb',
port: '3306',
username: 'admin',
password: 'xxxxxxxx'
}
var Batter = Waterline.Collection.extend({
adapter: 'mysql',
attributes: {
name: {
type: 'string',
required: true
}
}
});
new Batter({ tableName: 'batters', adapters: { mysql: mysql }}, function (err, Model) {
Model.findAll().exec(function(err, batters) {
// Now we have an array of users
});
});

Related

makes a database connection in the constructor using Knex

I am trying to implement knex connection below into an equivalent DB class. I searched but did not find any example implementation.
var knex = require('knex')({
client: 'pg',
connection: {
host: '127.0.0.1',
user: 'your_database_user',
password: 'your_database_password',
database: 'myapp_test'
},
pool: { min: 0, max: 7 }
})
let knex = require("knex");
class Database {
constructor(connection) {
this.connection = connection;
}
connect(option = {}) {
this.instance = knex(Object.assign(this.connection, option));
}
}
let db = new Database({
connection: {
host: '127.0.0.1',
user: 'your_database_user',
password: 'your_database_password',
database: 'myapp_test'
}
});
db.connect({
pool: { min: 0, max: 7 },
client: 'pg'
});

Mongoose nodejs - authentication failed trying to connect to mongodb docker

I'm trying to connect to a mongodb container using mongoose. This is my docker-compose:
version: "3"
networks:
mongonet:
services:
mongodatabase:
image: mongo
container_name: mongodatabase
ports:
- 27017:27017
environment:
- MONGO_INITDB_DATABASE=admin
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
networks:
- mongonet
mongojs:
depends_on:
mongodatabase:
condition: service_started
container_name: mongojs
build: .
ports:
- 8080:8080
environment:
- MONGO_URI=mongodb://mongodatabase:27017/test
networks:
- mongonet
Containers start and work ok, but problems appear when using mongoose:
const mongoose = requrie('mongoose')
const {MONGO_URI} = require('./../config/env')
exports.__mongo_ini = async function () {
const connectOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try {
await mongoose.connect(MONGO_URI, connectOptions)
console.info(`===> Connected to database ${MONGO_URI}`)
}
catch(err) {
console.warn(`===> Couldn't connect: ${err}`)
}
}
When using the env URI mongodb://mongodatabase:27017/test It says connected. But then If I try to find a model:
await models.Star.find().catch(r => r)
I get the error:
MongoServerError: command find requires authentication
at Connection.onMessage (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:203:30)
at MessageStream.<anonymous> (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:63:60)
....
ok: 0,
code: 13,
codeName: 'Unauthorized',
[Symbol(errorLabels)]: Set(0) {}
}
My model:
const starSchema = new mongoose.Schema({
starName: {
type: String,
unique: true,
required: true
},
image: {
type: String
},
designation: {
type: String
},
constelation: {
type: String
},
named: {
type: Date
},
timeStamp: {
type: Date,
default: Date.now()
}
})
const Star = mongoose.model('Star',starSchema)
module.exports = Star
Tried to add a mongo entrypoint volume in my docker compose:
volumes:
- ./mongo-entrypoint/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
Mongo-init.js:
db.getSiblingDB('admin').createUser({
user: 'testuser',
pwd: 'testpass',
roles: [
{
role: 'readWrite',
db: 'test'
}
]
})
db.getSiblingDB('test').createCollection('collection_test');
So I try to connect changing the mongo uri to use user and password:
MONGO_URI=mongodb://testuser:testpass#mongodatabase:27017/test
But It says authentication failed when trying to connect to the mongo uri and the mongo entrypoint doesn't seem to run:
Couldn't connect: MongoServerError: Authentication failed.
I've tried so many things and none of them work. All help is appreciated.
Try this code in node js
database.js
require("dotenv").config();
const mongoose = require("mongoose");
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connection SUCCESS");
} catch (error) {
console.error("MongoDB connection FAIL");
}
};
module.exports = connectDB;
.env
MONGO_URI=your_mongodb_url
Create a models file
models.js
const mongoose = require("mongoose");
const CategorysSchema = new mongoose.Schema({
description: {
type: String,
lowercase: true,
},
name: {
type: String,
lowercase: true,
},
publishedAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("categorys_collection", CategorysSchema);
Find Models
const Category_Model = require("./models");
app.get("/", async (req, res) => {
try {
const Category = await Category_Model.find();
res.json(Category);
} catch (error) {
res.status(500).json({ message: error.message, status: "error" });
}
});

Nodejs MSSQL how to pool multiple databases simultaneously

I am building a massive intranet using NodeJS, converting from ASP.Net C#. I keep running into database errors about cannot use the connection while it is closing or connection must be opened etc. I am attempting to convert over to connection pooling but am running into issues with it since I am connecting with (currently) 6 different databases, and being new to Node MSSQL I am kind of at a loss for how to proceed.
Originally I was making a call to "runqueries()" passing in the config data, and from there opening a connection to the desired database. The connection details were stored in a JSON object in the database.js file. I am now trying to create the pool in the database.js file and return that as an object to connect.
//database.js
const sql = require('mssql');
// const Config = {
// MCAIntranet: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'MCAIntranet',
// options: { enableArithAbort: true }
// },
// DEV_Intranet: {
// server: 'mcasql',
// user: 'username',
// password: 'password',
// database: 'DEV_Intranet_Test',
// options: { enableArithAbort: true }
// },
// CMR: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'Corporate_Morning_Reports',
// options: { enableArithAbort: true }
// },
// Lansa: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'LANSA',
// options: { enableArithAbort: true }
// },
// Roles: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'dotNetRolesDB_New',
// options: { enableArithAbort: true }
// },
// PreAuth:{
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'PreAuth',
// options: { enableArithAbort: true }
// }
// }
const CORPIntranet = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'CORPIntranet',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const DEV_Intranet = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'CORPIntranet_Test',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const CMR = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'Corporate_Morning_Reports',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const Lansa = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'LANSA',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const Roles = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'dotNetRolesDB_New',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const PreAuth = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'PreAuth',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const Config = {
CORPIntranet: CORPIntranet(),
DEV_Intranet: DEV_Intranet(),
CMR: CMR(),
Lansa: Lansa(),
Roles: Roles(),
PreAuth: PreAuth()
}
module.exports = Config;
I am calling this using the code await dataQuery.runQuery(query, config.PreAuth);
and the runquery() code is
//dataQueries.js
let sql = require('mssql');
const runQuery = async (query, database) => {
try {
// await sql.connect(database);
// let request = new sql.Request();
let recordset = await database.query(query);
return recordset;
} catch (ex) {
console.log(ex);
{ error: "dataQueries.js 17" + ex.Message };
return "False";
}
finally{
sql.close();
}
}
I know that I don't need the "sql.close()" at the end but I am in the process of conversion. I am now getting a typeError: database.query is not a function.
If you could point out where my fault lies in this, and better yet link a good tutorial that assumes neophyte status of the reader, that would be excellent.
Thanks in advance.
EDIT
In my runQuery() function I changed the code to
let pool=await database();
let recordset = await pool.query(query);
which now allows the query to run. But is this the correct method and will it prevent errors on multiple database connections?
I solved this problem in the simplest fashion possible. I switched from using the mssql module to sequelize.js which gives a level of abstraction from the database access and connectivity, and simplifies access to multiple databases along with database types (MSSQL, Postgres, MongoDB etc)

Certificate error when connecting to SQL Server

When trying to connect to SQL Server, I get the following error:
(node:9364) UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to 10.120.6.11:1433 - self signed certificate
When I use SQL Server 2014, it works normally.
Note: You need a vpn to connect.
Code:
const config = {
port: parseInt(process.env.DB_PORT, 10),
server: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_Database,
stream: false,
options: {
trustedConnection: true,
encrypt: true,
enableArithAbort: true,
trustServerCertificate: false,
},
}
sql.connect(config).then(pool => {
if (pool.connecting) {
console.log('Connecting to the database...')
}
if (pool.connected) {
console.log('Connected to SQL Server')
}
})
I had the same error message (Failed to connect to xxx:1433 - self signed certificate). Then I used trustServerCertificate: true. This fixed the error for me.
I encountered the same problem on my project. I manage to solve the problem by adding trustServerCertificate: true
Example (NestJS and TypeORM usage):
TypeOrmModule.forRoot({
type: 'mssql',
host: 'localhost\\SQLEXPRESS',
username: 'sa',
password: 'root',
database: 'DB',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
extra: {
trustServerCertificate: true,
}
}),
What works with me, with the full script:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'P#ssw0rd',
server: 'WIN-N4J1057LVFV',
database: 'WIN-PAK_ALL',
synchronize: true,
trustServerCertificate: true,
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from cardHistory', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
If you're using a connection string:
sql.connect('Server=localhost,1433;Database=database;User Id=username;Password=password;Trusted_Connection=True;TrustServerCertificate=True;');

TypeError: Cannot read property 'define' of undefined

i try to change my Db from mongodb to mysql, i use sequelize instead of mongoose, and i got this error, i created the User.js model with sequelize format, but something wrong and i don't know why
const User = sequelize.define('users', {
^
TypeError: Cannot read property 'define' of undefined"
Here is my code:
server.js
const Sequelize = require('sequelize');
// DB Config
const db = require('./config/keys');
// Connect to MySql
const sequelize = new Sequelize(db.database, db.user, db.password, {
host: db.host,
dialect: 'mysql',
port: db.port
});
// Test the connection
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
const serverDB = {};
serverDB.sequelize = sequelize;
serverDB.Sequelize = Sequelize;
module.exports = serverDB;
Users.js
const serverDB = require('../server');
const sequelize = serverDB.sequelize;
const Sequelize = serverDB.Sequelize;
const User = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
avatar: {
type: STRING
},
date: {
type: Sequelize.DATE,
defaudefaultValue: Sequelize.NOW
}
});
sequelize.models.modelName
// sequelize.sync()
// .then(() => {
// console.log('User db and user table have been created')
// });
module.exports = User;
You should add
const Sequelize = require('sequelize');
in your client too.
And only export and use the lowercase sequelize.
And ensure relative path of server.js is good.

Resources