I am using Node js to try to connect to MongoDB. Here are the related code snippets:
{
"port": 3001,
"appPort": 8080,
"host": "localhost:3001",
"protocol": "http",
"allowedOrigins": ["*"],
"domain": "http://localhost:3001",
"basePath": "",
"mongo": "mongodb://100.10.10.10:27017/database",
"mongoConfig": "",
"mongoCA": "",
"mongoSecret": "--- change me now ---"
}
MongoClient.connect(dbUrl, {useUnifiedTopology: true}, function(err, client) {
if (err) {
console.log(err);
debug.db(`Connection Error: ${err}`);
unlock(function() {
throw new Error(`Could not connect to the given Database for server updates: ${dbUrl}.`);
});
}
db = client.db(client.s.options.dbName);
debug.db('Connection successful');
}
When I use 'npm start' to start the server, I got this error:
MongoServerSelectionError: connect EACCES 100.10.10.10:27017
at Timeout._onTimeout (formio\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { '100.10.10.10:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
I have tried to enable/disable the firewall but the results still don't change. Could you help me fix it?
Thanks
More information about the repository:
https://github.com/formio/formio
https://github.com/Jobin-S/shopping-cart/blob/master/config/connection.js
please look this repository you can see the example.
Make an config file and require it in app.js
const mongoClient = require('mongodb').MongoClient
const state ={
db:null
}
module.exports.connect = (done) => {
const url = 'mongodb://localhost:27017';
const dbName = 'shopping';
mongoClient.connect(url,{ useUnifiedTopology: true }, (err, data) => {
if(err) return done(err)
state.db = data.db(dbName)
done()
})
}
module.exports.get = function(){
return state.db
}
after making this config file.
require config file and require in app.js file and write the code below
var db = require('./config/connection')
db.connect((err)=>{
if(!err) console.log("Database connected successfully");
else console.log(`Connection Error: ${err}`);
})
after that you can use database in any file.
const db = require('../config/connection')
addProduct: (product) => {
return new Promise((resolve, reject) => {
product.Price = parseInt(product.Price)
db.get().collection(collection_name).insertOne(product).then((data) => {
resolve(data.ops[0]._id)
})
})
}
Related
When I try to connect mongodb with node I get this error.(In picture)
In many tutorial I have seen the solution of the problem can be found by whitelisting the ip address. but trust me I did but nothing happened.
This is my code
const { MongoClient, ServerApiVersion } = require("mongodb");
// async function listDatabases(client){
// databasesList = await client.db().admin().listDatabases();
// console.log("Databases:");
// databasesList.databases.forEach(db => console.log(` - ${db.name}`));
// };
async function main() {
/**
* Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri =
"mongodb+srv://bran:R8VP2F3ZvEZWRi5l#cluster0.hd6phlm.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
try {
// Connect to the MongoDB cluster
await client.connect();
// Make the appropriate DB calls
await listDatabases(client);
} catch (e) {
console.error("the error: ", e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function listDatabases(client) {
databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach((db) => console.log(` - ${db.name}`));
}
This is my code
This is the error I am getting:
MongoServerSelectionError: connect ETIMEDOUT 15.206.14.158:27017
at Timeout._onTimeout (E:\node-mongo-connect\node_modules\mongodb\lib\sdam\topology.js:293:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-mg9lmct-shard-00-00.hd6phlm.mongodb.net:27017' => [ServerDescription],
'ac-mg9lmct-shard-00-01.hd6phlm.mongodb.net:27017' => [ServerDescription],
'ac-mg9lmct-shard-00-02.hd6phlm.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-hltwao-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
This is the error I am getting
I faced this issue a week ago. When I add my corrent Ip address in the list of network accesses in monogo atles, the issue was fixed. The important thing to mention that the 0.0.0.0 was not working.
I'm totally green with it all. Sorry, but I cant get this thing to work at all node.js + arangojs >
const myColl = async () => {//new Promise((resolve, reject) => {
try {
const db = await new Database({
url: "http://localhost:8529",
databaseName: "testDB",
auth: {username: "userTest", password: "userTest"},
});
console.log(db)
try {
let collection = await db.collections();
console.log(collection);
} catch (err) {
console.log(err);
}
} catch (err) {
console.log("Failed to login db ", err)
return
}
}
myColl()
I just end up with :
Database {_analyzers: Map(0), _collections: Map(0), _graphs: Map(0), _views: Map(0), _connection: Connection, ...}
icAccountController.js:23
Error: connect ECONNREFUSED ::1:8529 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {errno: -4078, code: "ECONNREFUSED", syscall: "connect", address: "::1", port: 8529, ...}
I am using mongo 5.0.1 and node 17.2.0
this is my code
If I connect want to connect with atlas with this code it runs successfully but when I try to connect with the local Database it gives this error.
const { MongoClient } = require("mongodb");
async function main(){
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
try{
await client.connect();
await listDatabases(client);
} catch (e){
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function listDatabases(client) {
databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};
This is the error I am getting.
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (D:\web development\nodeDemo\node_modules\mongodb\lib\sdam\topology.js:330:38)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
use this as your uri
const uri = "mongodb://127.0.0.1:27017";
I solved this by enabling the IPv6 in the mongodb.config
more info here https://www.mongodb.com/docs/manual/reference/configuration-options/#mongodb-setting-net.ipv6
Use this URL:
mongodb://127.0.0.1:27017
Instead of:
mongodb://localhost:27017
I am using mysql2 package with the Express Framework, deployed over AWS Lamda. I have the provisioned concurrency set to 3 for Aws Lambda.
I am not directly connecting to MySQL. I have RDS Proxy in between.
I am getting the following error, randomly.
{
"errorType": "Error",
"errorMessage": "connect ETIMEDOUT",
"code": "ETIMEDOUT",
"errorno": "ETIMEDOUT",
"syscall": "connect",
"fatal": true,
"stack": [
"Error: connect ETIMEDOUT",
" at Connection._handleTimeoutError (/var/task/node_modules/mysql2/lib/connection.js:178:17)",
" at listOnTimeout (internal/timers.js:554:17)",
" at processTimers (internal/timers.js:497:7)"
]
}
Following is what my code looks like:
var AWS = require("aws-sdk");
const mysql = require('mysql2');
class DBConnection {
constructor() {
var signer = new AWS.RDS.Signer({
region: 'us-east-1',
hostname: process.env.DB_HOST,
port: 3306,
username: process.env.DB_USER
});
let connectionConfig = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
database: process.env.DB_NAME,
ssl: 'Amazon RDS',
authPlugins: { mysql_clear_password: () => () => signer.getAuthToken() }
};
this.db = mysql.createConnection(connectionConfig);
}
query = async (sql, values) => {
return new Promise((resolve, reject) => {
this.db.execute(sql, values, (error, result) => {
if (error) {
reject(error);
return;
}
resolve(result);
});
});
}
}
module.exports = new DBConnection().query;
const results = await query('SELECT COUNT(*) AS total_listens FROM analytics WHERE event_name="PLAYED"');
Any clue where the issue can be?
With AWS Lambda function it's better to use mysql.createPool instead of mysql.createconnection. I don't know what's the specific reason but using mysql.createconnection instead of mysql.createPool has caused problems for me as well. It's also necessary to release the connection when the query goes successful.
I'm trying to write tests for a node/postgresSQL setup. Currently at the step where I create a table and then seed the table with users. I have an async function called createUserTable and then a second async function called seedUserTable, but when I run them I get the error 'relation "public.user" does not exist. I'm really confused as to why my second async function is running before the first one has finished.
Here is my code
const { Pool } = require('pg');
const { DB_HOST, DB_USERNAME, DB_PASSWORD, DB_PORT, DB_TEST_DATABASE } = require('./config');
const pool = new Pool({
host: DB_HOST,
port: DB_PORT,
user: DB_USERNAME,
password: DB_PASSWORD,
database: DB_TEST_DATABASE,
});
const createUserTable = async () => {
console.log('createUserTable')
try {
const newUserTable = await pool.query(`
CREATE TABLE public.user
(
user_id SERIAL PRIMARY KEY UNIQUE NOT NULL,
username VARCHAR(35) UNIQUE NOT NULL
);
`);
console.log(newUserTable);
} catch (error) {
console.error(error.message);
}
}
const seedUserTable = async () => {
console.log('seedUserTable')
try {
const seedUserTable = await pool.query(`
INSERT INTO public.user(username)
VALUES (
$1
),
(
$2
)
RETURNING *
`,
[
'demo',
'demo2',
]
);
console.log(seedUserTable);
} catch (error) {
console.error(error.message);
}
}
createUserTable();
seedUserTable();
This is what I'm getting in the terminal.
$ node index2.js
createUserTable
seedUserTable
relation "public.user" does not exist
Result {
command: 'CREATE',
rowCount: null,
oid: null,
rows: [],
fields: [],
_parsers: undefined,
_types: TypeOverrides {
_types: {
getTypeParser: [Function: getTypeParser],
setTypeParser: [Function: setTypeParser],
arrayParser: [Object],
builtins: [Object]
},
text: {},
binary: {}
},
RowCtor: null,
rowAsArray: false
}
Edit: Removed the async from the two functions and wrapped the call in an async function like this.
(async () => {
await createUserTable();
setTimeout(() => {
console.log('5000 ms timeout');
}, 5000);
await seedUserTable();
})();
Currently getting this error:
createUserTable
Promise { <pending> }
seedUserTable
Promise { <pending> }
(node:19684) UnhandledPromiseRejectionWarning: error: relation "public.user" does not exist
5000 ms timeout
I suggest to remove all async functions that you've added and do this down below:
(async() => {
await createUserTable();
await seedUserTable();
})();
i am just thinking that the problem maybe from the postgress naming when it creates tables
try checking the name of the tables in the database after it's creation