I am new to backend service. I have been trying to make a connection to arangodb from node server. I have a created a basic query in arangodb. the user auth in arangodb is so complicated and there are very few tutorials for node and arangadb combo. I have posted my code below. I have found this example online.
DataService.js
var arangojs = require('arangojs');
// Const variables for connecting to ArangoDB database
const host = '192.100.00.000'
const port = '8529'
const username = 'abcde'
const password = 'abcde'
const path = '/_db/_system/_api/'
const databasename = 'xyzm_app'
// Connection to ArangoDB
var db = new arangojs.Database({
url: `http://${host}:${port}${path}${databasename}`,
databaseName: databasename
});
db.useBasicAuth(username, password);
//console.log(db);
module.exports = {
getAllControllers : function(){
return db.query('For x IN {user_details} RETURN NEW {
id: x._user_details/7977010,
name: x.char_ctrl_username,
email:x.char_ctrl_email
}')
.then(cursor => {
return cursor.all()
});
}
query in db
From the arangojs README:
// Or using a fully qualified URL containing the database path
const db = new Database({
url: `http://${username}:${password}#${host}:${port}/_db/${database}`,
databaseName: false // don't automatically append database path to URL
});
databaseName: string (Default: _system)
Name of the active database.
If this option is explicitly set to false, the url is expected to contain the database path and the useDatabase method can not be used to switch databases.
So you either specify the full path like http://host:port/_db/dbname and set databaseName: false, or you use http://host:port and either specify databaseName: "dbname" or useDatabase("dbname").
/_api should not be part of the path, ever. arangojs knows where to find the API endpoint and does it for you.
var arangojs = require('arangojs');
// Const variables for connecting to ArangoDB database
const host = '127.0.0.1'
const port = '8529'
const username = 'xyz'
const password = 'xyz'
const databasename = 'sgcdm_app'
// Connection to ArangoDB
db = new arangojs.Database({
url: `http://${host}:${port}`,
databaseName: databasename
});
db.useBasicAuth(username, password);
db.listCollections().then(function(res) {
res.forEach((coll, i) => {
console.log(`${i+1}. ${coll.name} (ID=${coll.id}, system=${coll.isSystem})`)
});
}, function(err) {
const res = err.response.body;
console.log(`Error ${res.errorNum}: ${res.errorMessage} (HTTP ${res.code})`);
});
On success (database exists):
1. first (ID=264349479, system=false)
2. test (ID=264349463, system=false)
On error (unknown database):
Error 1228: database not found (HTTP 404)
cross-post from GitHub
Related
After following the reference links to trace mysql query
https://github.com/aws/aws-xray-sdk-node/issues/275
https://github.com/aws/aws-xray-sdk-node/issues/6
I have tried to log mysql2 logs but it does not work with aws-xray-sdk and aws-xray-sdk-node npm packages.
I know that aws-xray works well with mysql but it does not work and trace with mysql2.
Following is my code of database connection.
const mysql2 = require("mysql2");
const awsXRay = require("aws-xray-sdk");
const captureMySQL = require('aws-xray-sdk-mysql');
const mysql = captureMySQL(mysql2);
module.exports.getConnection = async (client, service) => {
const poolConfig = {
host: mysqlHost,
port: mysqlPort,
user: mysqlUser,
password: mysqlPass,
database: mysqlDb,
multipleStatements: true
};
const connection = mysql.createConnection(poolConfig);
connection.connect();
// create promise to use await
connection.query = util.promisify(connection.query);
return connection;
};
I have tried to logged the queries but it does not work anyway.
Thank you for to put some light on this issue.
I'm trying this approach, but I'm not sure if that creates a new connection every time.
getMongoClient.js
const { MongoClient } = require('mongodb');
const serverURL = process.env['mongoServerURL']
module.exports = async function (){
const mongoClient = await new MongoClient(serverURL);
await mongoClient.connect();
return mongoClient;
}
then in the app.js
const getMongoClient = require("./_helpers/getMongoClient.js")
module.exports = getMongoClient();
then in a database service.js
async function syncGuilds(client){
const mongoClient = await require("../app.js")
... some database operations
}
module.exports = syncGuilds
Node modules are singleton by themselves, you don't need to worry about them. When your modules is once evaluated, it won't be evaluated again. So you will always receive same instance of the module i.e it won't create multiple instance of mongo connection.
You can check this and this link for more details.
It won't create a new connection every time, If you want you can specify max connection pool size in options default value is 5. Check below link
https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#connection-pool-configuration
const mongodb = require("mongodb");
let client = new mongodb.MongoClient(
"url",
{
tls: true,
auth: { user: "myuser", password: "mypassword" },
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: 1,
maxPoolSize: 1,
}
);
I am new in Cloudant db. I need to migrate from Mamp db to Cloudant. I am getting form data and inserting it to DB but with Cloudant I am not able to understand insert command as it work differently (Object base save). How can I make a Db connection?
The insert code is given below:
const mysql = require("mysql");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { promisify } = require ('util');
// const db = mysql.createConnection({
// host: process.env.DATABASE_HOST,
// port: process.env.DATABASE_PORT,
// user: process.env.DATABASE_USER,
// password: process.env.DATABSE_PASSWORD,
// database: process.env.DATABASE
// });
Cloudant = require('#cloudant/cloudant');
cloudAntConfig = {
url: process.env.CLOUD_ANT_URL,
apiKey: {iamauth: {iamApiKey: process.env.CLOUD_ANT_APIKEY}},
database: process.env.CLOUD_ANT_DB
};
exports.assessment = (req,res) => {
console.log(req.body);
// console.log(user.User_ID );
const { TeamName, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10, question11, question12, question13, question14, question15, question16, question17, question18, question19, question20, question21, question22, question23, question24, question25, question26, question27, question28, question29, question30, question31, question32, question33, question34, question35 } = req.body;
// console.log(parseInt(question3)+parseInt(question4));
// some code about data goes here
db.query('INSERT INTO assessment_result SET ?',{User_Id : 1,Team_Name : TeamName, Dimension_1_Score : (dime_1_total/25)*100, Dimension_2_Score : (dime_2_total/50)*100, Dimension_3_Score : (dime_3_total/50)*100, Dimension_4_Score : (dime_4_total/50)*100, Total_Score : final_total, Total_Score_Persentage : (final_total/175)*100 },(error,results)=>{
// res.render('register');
})
}
The Getting Started section of the #cloudant/cloudant README shows how to insert a document into a Cloudant database.
const Cloudant = require('#cloudant/cloudant');
cloudAntConfig = {
url: process.env.CLOUD_ANT_URL,
plugins: { iamauth: { iamApiKey: process.env.CLOUD_ANT_APIKEY } }
}
const cloudant = Cloudant(cloudAntConfig);
const db = cloudant.use(process.env.CLOUD_ANT_DB)
// ...
db.insert({User_Id: 1, /* etc the rest of your document content */}, (err, data) => {})
Probably worth noting though that #cloudant/cloudant is deprecated and if you are writing new code you should consider using #ibm-cloud/cloudant.
I've tried to develop a server with nodejs that is link with NOSQL DB, in particular I've developped it with MONGODB. I'm not sure I manage to connect it well due to the fact if I run the code below it should return the id of the element inserted but it prints in output a blank, in the case I substitute the async with a normal development it return the following error "
MongoError: Topology is closed, please connect " .I've tried to use the lines of code with /the comment below the code/ but it returns another error.
I think I don't connect well mongodb with my server but I don't know I follow the commands deliver in mongodb step by step.(create a cluster(free),create a user,create a db and then a collection and then connect use the information set before.)
I said it because I refresh the cluster on mongodb but I don't obtain any change
const MongoClient = require('mongodb').MongoClient;
const password = encodeURIComponent('22');
const user=encodeURIComponent('id');
const dbs = encodeURIComponent('users');
const uri = "mongodb+srv://${user}:${password}#cluster/${dbs}?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology:true, connectTimeoutMS: 30000 , keepAlive: 1});
(async()=>{
await client.connect();
const databse=client.db("users");
const collection=databse.collection("readers");
const result= await collection.insertOne( {
"name":"Chocolate",
"ingredients":[
"eggs","chocolates"
]
});
console.log(result.insertedId);
//client.close();
});
/*
client.connect(err => {
const collection2 = client.db("users").collection("readers");
// perform actions on the collection object
var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" };
collection2.insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 record inserted");
//client.close();
});
});
*/
I see a few problems with the code.
There is no reason for you to use encodeURIComponent with static strings. But hopefully, that's just a placeholder for some real credentials that are going to come from an environment variable.
The variable uri is being assigned with a static string that contains a templating pattern, but it is using double quotes instead of backticks, so it won't interpolate the variables, which in turn will generate an invalid connection string.
The same variable uri, after having replaced the double quotes " with the backticks ` might still not work because of the strange hostname "cluster" that should come from some sort of settings of env var as well.
The code seems to have the intent of using an Immediately Invoked Function Expression (IIFE for short) but it is in fact not even calling the function because the parenthesis pair is missing after the function block.
Assuming your credentials are correct the updated code below should do the trick for you:
const MongoClient = require('mongodb').MongoClient
const password = encodeURIComponent('22')
const user = encodeURIComponent('id')
const dbName = encodeURIComponent('users')
const host = process.env.MONGO_HOST || 'localhost' // or whatever is the hostname you want
const uri = `mongodb+srv://${user}:${password}#${host}/${dbName}?retryWrites=true&w=majority`
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, connectTimeoutMS: 30000, keepAlive: 1 })
;(async () => {
await client.connect()
const databse = client.db('users')
const collection = databse.collection('readers')
const doc = {
name: 'Chocolate',
ingredients: [
'eggs', 'chocolates'
]
}
const result = await collection.insertOne(doc)
console.log({ result })
console.log(result.insertedId)
client.close()
})()
I have select query that pulls a row of a data from a largeObject stored in a PostgreSQL table. The particular piece of data in the field is a html file.
I can output the name of the field of data into the console which appears as 16543 (for 16543kB).
So, my burning question is how I can return the actual contents (html) so that I can subsequently export it as one object and send it to the browser.
I am using node and express heres my source code so far:
var database = require('../database/postgresDB.js');
var pg = require('pg');
var html = {};
var connectionString = "postgres://dabladmin:dabldem#localhost:5432/dablpatient";
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('SELECT * FROM htmlfiles WHERE id = 1', function(err, result){
console.log(JSON.stringify(result));
console.log(result.rows[0].htmlfile);
html = result.rows[0].htmlfile;
//return result.rows[0].htmlfile;
//console.dir(html);
});
module.exports = html;
This cannot be done directly. You need to export a function which will return the promise.
Following is an idea of how it can be done. Note: The code is not tested.
// htmlfile.model.js
const promise = require('bluebird'); // or any other Promise/A+ compatible library;
const initOptions = {
promiseLib: promise // overriding the default (ES6 Promise);
};
const pgp = require('pg-promise')(initOptions);
// Database connection details;
const cn = {
host: 'localhost', // 'localhost' is the default;
port: 5432, // 5432 is the default;
database: 'myDatabase',
user: 'myUser',
password: 'myPassword'
};
const db = pgp(cn); // database instance;
const getHtml = id => db.oneOrNone('SELECT * FROM htmlfiles WHERE id = $1', id);
module.exports = getHtml;
Inside some.controller.js:
const html_model = require('./htmlfile.model.js');
html_model.getHtml(1)
.then(data => {
if(data) {
// record found
res.send(data.htmlfile);
} else {
// record not found, do something else
}
})
.catch(error => {
// an error occurred
});