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
Related
const amqp = require("amqplib");
const config = require("./config/config");
class Producer {
channel;
async createChannel() {
const connection = await amqp.connect(config.rabbitMQ.url);
this.channel = await connection.createChannel();
}
async publishMessage(routingKey, message) {
if (!this.channel) {
await this.createChannel();
}
const exchangeName = config.rabbitMQ.exchangeName;
await this.channel.assertExchange(exchangeName, "direct");
const logDetails = {
logType: routingKey,
message: message,
dateTime: new Date(),
};
await this.channel.publish(
exchangeName,
routingKey,
Buffer.from(JSON.stringify(logDetails))
);
console.log(
`The new ${routingKey} log is sent to exchange ${exchangeName}`
);
}
}
module.exports = Producer;
Error
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
Error: connect ECONNREFUSED 127.0.0.1:5672
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5672
}
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 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)
})
})
}
Database code:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const mongoConnect = callback => {
MongoClient.connect('mongodb+srv://shubhamt10:shubham123#cluster0-g2s9w.mongodb.net/test?retryWrites=true',
{ useNewUrlParser: true})
.then(client => {
console.log('Connected!');
callback(client);
})
.catch(err => {
console.log(err);
});
}
module.exports = mongoConnect;
app.js code
const mongoConnect = require('./util/database');
mongoConnect(client => {
console.log(client);
app.listen(3000);
});
I am getting this error :
{ MongoNetworkError: connection 5 to cluster0-shard-00-02-g2s9w.mongodb.net:27017 closed
at TLSSocket. (E:\Node JS\Final Project\node_modules\mongodb-core\lib\connection\connection.js:276:9)
at Object.onceWrapper (events.js:285:13)
at TLSSocket.emit (events.js:202:15)
at _handle.close (net.js:611:12)
at TCP.done (_tls_wrap.js:390:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Please check the network access Of your MongoDB atlas account
click on the Allow access from anywhere button after that click on confirm button to change the IP address 0.0.0.0/0 now you can use your connection string on any system