i'd like to use https://github.com/OptimalBits/node_acl module with http://sailsjs.org Framework. So I configured sails to use mongodb like this :
In /config/connection.js
mongodb: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
user: '',
password: '',
database: 'acl'
}
And in /config/models.js
{
connection: 'mongodb',
migrate: 'safe'
}
Now I have to configure the acl module, so in /api/controllers/AclController.js i have :
var acl = require('acl');
acl = new acl(new acl.mongodbBackend(dbInstance, 'acl_'));
module.exports = {
addUserRoles : function(req, res) {
acl.addUserRoles('joed', 'guest', function(err,data){
return res.json({err:err, data:data});
});
}
Now how can I get the value of dbInstance to instanciate acl?
Note : I installed acl and sails-mongo dependencies...
Thank you for your help
node_acl seems to depend on the mongodb driver, which will have different methods than the Waterline ORM that sails is using.
That said, you should be able to create 2 connections to your mongo instance, one via the node_acl library and another for waterline/sails. As long as your sails models are correctly defined they should be able to live side by side. If you want you can even prefix your node_acl tables, and completely ignore them in sails.
Related
I have a node.js express api which I host on heroku. It connects to mongodb atlas via mongoose as follows
mongoose.connect(
`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PWD}#${process.env.MONGO_HOST}/${process.env.MONGO_DEFAULT_DB}?retryWrites=true`, {
useNewUrlParser: true,
autoReconnect: true,
keepAlive: 300000,
connectTimeoutMS: 300000,
socketTimeoutMS: 300000
}
)
.then(result => {
console.log('Connected and listening to requests!');
app.listen(process.env.PORT || 3000);
.catch(err => console.log(err));
I want to use Atlas MongoDB Cloud's whitelist for the Heroku app, instead of opening access up to all. Heroku doesn't have fixed a IP address but makes them possible via an add-on called Fixie Socks, which acts as a proxy for outbound traffic.
How can I use this add-on to get the connection to work? The documentation gives several examples on how to connect to other services and databases, but there is no help on mongodb. All examples use the FIXIE_SOCKS_HOST which contains the SOCKSV5 proxy URL, user, pass and port, but I'm at a loss on how to use it in conjunction with the mongoose.connect method.
This question has been asked before, but when a different add-on was used (Fixie vs Fixie Socks), which didn't work.
I tried Fixie Socks but couldn't get it to work. But managed to successfully connect to Mongodb Atlas database with Quota Guard's static IP addresses following this documentation:
https://support.quotaguard.com/support/solutions/articles/12000066411-how-to-connect-to-mongodb-using-quotaguard
The trick is to use the use mongodb atlas' connection string without +srv command. To do that use an older driver version and it will provide you a connection string with 3 replica servers (each with 27017 port). Then create 3 tunnels at the Quota Guard dashboard.
Make sure you download the gqtunnel package and extract it your app's root folder. Then you just have to add the bin/qgtunnel to your procfile.
Example:
web: bin/qgtunnel your-application your arguments
I manage to connect from Heroku + node.js + Fixie SOCK add-on to MongoDB Atlas. A few parameters in MongoClient need to be set to direct MongoDB traffic to Fixie proxy. This is the snippet:
const {MongoClient, ServerApiVersion} = require('mongodb');
const username = process.env.USERNAME;
const password = process.env.PASSWORD;
const host = process.env.MONGO_DB_HOST;
const uri = "mongodb+srv://" + username + ":" + password + "#" + host + "/?retryWrites=true&w=majority";
const fixieData = process.env.FIXIE_SOCKS_HOST.split(new RegExp('[/(:\\/#/]+'));
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
proxyUsername: fixieData[0];
proxyPassword: fixieData[1];
proxyHost: fixieData[2];
proxyPort: fixieData[3];
});
Some of the MongoDB client connection options can be found here:
https://mongodb.github.io/node-mongodb-native/4.5/interfaces/ConnectionOptions.html
With modern versions of Mongoose, you can include the proxy-related driver options in the options object on mongoose.connect, and this works both with and without the +srv URL modifier.
const mongoose = require('mongoose');
const fixieData = process.env.FIXIE_SOCKS_HOST.split(new RegExp('[/(:\\/#/]+'));
mongoose.connect(process.env.DB_CONNECTION,
{
proxyUsername: fixieData[0],
proxyPassword: fixieData[1],
proxyHost: fixieData[2],
proxyPort: fixieData[3]
},
(error) => {
if (error){
console.log(error)
} else {
console.log('Connected to database')
}
}
)
I want to display and edit data from a existing PostgreSQL database in an Angular Web Application.
I am completely new to angular and stuff.
I downloaded pg and express already.
After a look on this page: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose
I figured I will need jugglingdb to connect the database to angular: https://npm.taobao.org/package/jugglingdb or https://www.npmjs.com/package/connect-jugglingdb
-> more specific: Juggling-db with postgres: https://npm.taobao.org/package/jugglingdb-postgres
So I created a new file called postgres.js:
var Schema = require('jugglingdb').Schema;
var schema = new Schema('postgres', {
database: 'mydatabase',
username: 'myusername',
host: 'myhostname', //I don't use the local user
port: XXXX,
password: s.password,
ssl: false
});
var Model = schema.define('Model', {
realNumber: {type: Number, dataType: 'float'}
});
Then I tried it with the help of this answer: Restful Api express postgres database
so I created a File called "dbconnector.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 1234
const db = require('./dbconnector')
// 'db' is exported from a file such as
// dbconnector.js.
app.get('/things', db.getThings)
//In dbconnector.js:
const Pool = require('pg').Pool
const pool = new Pool({
user: 'myuser',
host: 'myhost',
database: 'mydb',
password: 'mypassword',
port: 5432,
})
const getThings = (request, response) => {
pool.query('SELECT * FROM public.regulation',
(error, results) =>
{
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
module.exports = {
getThings
}
I have searched, read and tried a lot of tutorials.
But whatever I try - I just can't display the data from the database in the web applikation.
Any ideas how I shall proceed?
Do you know a complete guide (connecting the database and displaying the data?)
or do you have any links or tips?
Edit
Found this very useful Link to a download example: https://grokonez.com/frontend/angular/angular-6/angular-6-httpclient-postgresql-node-js-express-sequelize-crud-apis-post-get-put-delete
An Angular application typically runs in the browser, while your database lives on a server. In simple terms, you usually connect them up by building a backend to your application that exposes any required data to consumers via an API.
It looks like you are using NodeJS for your backend from the links that you posted, so you could look into creating a RESTful API using express.
I created db.js file into my node project
const environment = process.env.NODE_ENV || 'development';
const configuration = require('../knexfile')[environment]; var
database = require('knex')(configuration);
module.exports = database;
I call require('xxxxxx/db.js') where I need knex, to make sql query for Postgres database (through different files). It eats my postgres connections (reach 100 pq connections very soon). I checked it with this script code under Postgres database.
select
sum( numbackends )
from
pg_stat_database;
What is the best practice to use knex into nodejs ?
const Knex = require('knex');
const { host, user, password, database, port } = require('settings')
const knex = Knex({
client: 'pg',
connection: { host, user, password, database, port },
pool: { min: 0, max: 200 }
});
I suggest to use Knex.raw(sql, args) as much as possible. Just because Knex uses the connection pool and release. no need to worry about it.
Hope this will help you somehow.
const knex = require('knex')({
client: 'pg',
connection: {
host : '127.0.0.1',
port : 3306,
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test'
}
});
Source - https://knexjs.org/guide/#configuration-options
Iam trying to implement role based authentication with sails js and use node_acl middleware. Has anybody tried it before? What i see from acl documentation is
//Using the mongodb backend
acl = new acl(new acl.mongodbBackend(dbInstance, prefix));
How do I get the dbInstance object from SailsJs
I was just trying the same thing (not sure about the merits in that), and I managed to connect using the MongoDB Driver.
You have to
npm install mongodb --save
and then, assuming you have in your config/connections.js the following adapter information:
MyMongo: {
adapter: 'sails-mongo',
host: 'localhost', // defaults to `localhost` if omitted
port: 27017, // defaults to 27017 if omitted
user: '', // or omit if not relevant
password: '', // or omit if not relevant
database: 'someDB' // or omit if not relevant
},
You can now do the following:
var node_acl = require('acl');
var MongoClient = require('mongodb').MongoClient;
var dbInstance = "mongodb://"+sails.config.connections.MyMongo.host+":"+
sails.config.connections.MyMongo.port+"/"+sails.config.connections.MyMongo.database;
MongoClient.connect(dbInstance, function(error, db) {
//check for errors...
var mongoBackend = new node_acl.mongodbBackend(db, 'acl_');
var acl = new node_acl( mongoBackend );
acl.allow('role', 'model', 'action'); // Now you can do this...
}
I hope this helps. Notice I added the acl_ prefix so all the collections generated by ACL are discernible from other collections used by your models with sails.
I'm trying to create a mysql database to node.js server. I've installed mysql module through command prompt:
npm install mysql
Then I execute the following code:
var Client = require('mysql').Client;
console.log(Client);
Console display undefined. That is, Client is undefined. Please tell me why it is undefined?
I'm following this tutorial
http://utahjs.com/2010/09/22/nodejs-and-mysql-introduction/
Maybe the the tutorial is a little bit old. Just use the instruction on the node-mysql docs:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
And you should be able to connect to your MySQL database.
The node js APIs having been changing updating a lot in recent past, so it is highly possible that the tutorial you have been following is out of date according to the version you are using. You can follow the code example here I am updating or you may refer to something else, the only part that matters is it should work at minimum cost.
var mysql = require('mysql');
app.use( connection(mysql, {
host: 'myhost',
user: 'user_name',
password: 'password',
port: 3306, //port mysql
database: 'database_name',
multipleStatements: 'true' //false by default
}, 'pool'));
req.getConnection(function(err, connection) {
connection.query("SELECT * FROM `table_name`;",function (error,row){
if(!error){
//do something.....
}
else console.log("Error : "+err);
});
//do something else...
});
Thank you...!