MongoDB refusing to connect using NodeJS - node.js

I have been struggling to connect to MongoDB for the past few hours now.
I have taken the code from the atlas documentation as seen below:
const { MongoClient } = require('mongodb')
const url =
'mongodb+srv://user:pass#mmmcluster.axapu.mongodb.net/appname?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true'
const client = new MongoClient(url)
async function run() {
try {
await client.connect()
console.log('Connected correctly to server')
} catch (err) {
console.log(err.stack)
} finally {
await client.close()
}
}
run().catch(console.dir)
I cannot for the life of me figure out why I keep getting the error below:
MongoServerSelectionError: connect ETIMEDOUT 157.241.16.152:27017
at Timeout._onTimeout (E:\Documents\Github\#test\node_modules\mongodb\lib\sdam\topology.js:306:38)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
For the record:
All IP addresses are whitelisted on my database access list
I have turned off any firewalls that would be running over the internet, and whitelisted NodeJS on the windows firewall
No spaces or brackets are have been included in my password or username
The user has admin privileges on atlas
Any suggestions? I am out of ideas here and I don't want to have to install Compass as a workaround since ideally, all methods of connection should work.

I think you should take a look here:
const url =
'mongodb+srv://user:pass#mmmcluster.axapu.mongodb.net/appname?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true'
since there is this user and pass you might want to replace them with the actual username and password for the database.

Related

Node error connecting to SQL Server 2019 won't go away

i'm having some trouble connecting node to the database, it keeps throwing me an error of ssl and i tried a lot of different videos and stuff to see if it works but nothing does, here is what i'm currently doing
import sql from 'mssql'
const dbSettings = {
user: 'admin',
password: 'system',
server: 'localhost',
database: 'master',
options: {
trustedConnection: true,
encrypt: true,
trustServerCertificate: true,
},
}
async function getConnection() {
const pool = sql.connect(dbSettings)
const result = await sql.query("SELECT 1")
console.log(result)
}
getConnection()
i also tried this as well but didn't work either
async function getConnection() {
const pool = await sql.connect(dbSettings)
const result = await pool.request().query("SELECT 1")
console.log(result)
i also checked if the SQL Server authentication is enabled with windows and SQL Server and it is, i can log in into SQL Server with that info, but somehow is having trouble creating the connection, by the way, this is the error message it is showing me:
node_modules\mssql\lib\tedious\connection-pool.js:70
err = new ConnectionError(err)
^
ConnectionError: Failed to connect to localhost:1433 - 186B0000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1986
any tips or solution you can give me to solve this problem would be really helpful to me, thank you very much in advance.
EDIT
I noticed that the connection error only appears when i call the function getConnection if i remove it it doesn't appear, however i need to make sure that the connection was properly established and see the response from the database to move on
change encrypt: true to encrypt: false

MongooseError: Operation `x.findOne()` buffering timed out after 10000ms

I am using Discord.JS v13 for sharding, and I am using mongoose for the database.
I connect to mongoose in my sharding file (index.js) rather than in the bot.js because I need to use it there, but this isn't allowing me to get data from mongoose anywhere but index.js. I don't know why is this happening as this was perfectly fine a few days back and I haven't changed anything.
index.js (Sharding File)
// .....Sharding Manager
const dbURI = process.env.DBURI;
const mongoose = require("mongoose");
// noinspection JSCheckFunctionSignatures
mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
/models/user.js (Schema File)
const mongoose = require("mongoose");
const userinfo = new mongoose.Schema({
UserID: {
type: String || Number,
required: true,
},
/** Whole schema **/
});
const MessageModel = (module.exports = mongoose.model("muser_userinfo", userinfo));
scommands/filters.js (The File I want to use it at!)
const userinfo = require("../models/user.js");
const user_id = interaction.user.id;
const data = await userinfo.findOne({ UserID: user_id });
if (!data) {
//....
Error
7|muser | MongooseError: Operation muser_userinfos.findOne()` buffering timed out after 10000ms 7|muser | at Timeout.<anonymous> (/root/Bots/muser/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:20) 7|muser | at listOnTimeout (node:internal/timers:559:17) 7|muser | at processTimers (node:internal/timers:502:7)
I have tried everything you can possibly think of, used find() instead of findOne(), used .then() on connect, double-checked the credentials and what not!
The ShardingManager generally spawns a process for each shard (unless you specify otherwise). If you're only connecting to your Mongo database from the sharding file then your bot client won't have access to it.
Try connecting to your Mongo database from the client too, it shouldn't matter too much since Mongo supports multiple connections.
In my experience of using mongoose, its throwing an error because of low internet connection, but looking in other documents. this is what ive found that can help you
In my experience this happens when your database is not connected, Try checking out following things -
Is you database connected and you are pointing to the same url from your code.
check if your mongoose.connect(...) code is loading.
I faced this issue where I was running the node index.js from my terminal and mongoose connect code was into different file. After requiring that mongoose code in index.js it was working again. This is the source link --Biggest credit for #Abhishek Gangwar

OrbitDB can't replicate database on different peer

I have forced with problem in my p2p database orbitdb. Everything works fine while I did not move the database to another server.
const ipfsOptions = {
repo: './ipfs'
}
const ipfs = await IPFS.create(ipfsOptions)
const orbitdb = await OrbitDB.createInstance(ipfs, { directory: './orbitdb' })
try {
publicDB = await orbitdb.open("/orbitdb/zdpuB2kVAbJEk1aZBeeKcwz2ehfDaMWi3upkD3ZHwb15zesLF/hub")
console.log(publicDB.get('hello'))
} catch (err) {
console.log(err)
}
I created an orbit db on another computer and wanted to open from my computer, but it doesn't work, got TimeoutError: request timed out.
TimeoutError: request timed out
at maybeThrowTimeoutError (D:\Source\iprs-node\node_modules\ipfs-core-utils\cjs\src\with-timeout-option.js:35:15)
at D:\Source\iprs-node\node_modules\ipfs-core-utils\cjs\src\with-timeout-option.js:78:9
at runNextTicks (internal/process/task_queues.js:60:5)
at processTimers (internal/timers.js:497:9)
at async Object.read (D:\Source\iprs-node\node_modules\orbit-db-io\index.js:59:17)
at async OrbitDB.open (D:\Source\iprs-node\node_modules\orbit-db\src\OrbitDB.js:452:22)
at async initOrbit (D:\Source\iprs-node\services\orbitdb\index.js:26:20)
at async initAll (D:\Source\iprs-node\index.js:9:5) {
code: 'ERR_TIMEOUT'
}
Does anyone know how to fix it?
Or enlighten me, how this works?

MongooseError: Operation users.insertOne() buffering timed out after 10000ms” in Mongo Db atlas

I am currently working with node and mongoDB
here is my code
import dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
mongoose
.connect(
`mongodb+srv://OmniBotBuilder:${process.env.DBPASS}${process.env.DBUSER}.kx2vg.mongodb.net/${process.env.DBNAME}?retryWrites=true&w=majority`,
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
)
.catch(() => console.error("Unable to connect to DB"));
mongoose.connection.on("connected", () => {});
const Schema = mongoose.Schema;
const omniGamesSchema = new Schema({
discordId: Number,
steamId: Number,
});
const omniGamesModel = mongoose.model("omniGamesSchema", omniGamesSchema);
const createNewUser = (discordId, steamId) => {
const newUserMap = new omniGamesModel({
discordId: discordId,
steamId: steamId,
});
newUserMap.save((err) => {
if (err) {
console.error(err);
}
});
};
export { createNewUser };
and the error i am getting is this one
MongooseError: Operation omnigamesschemas.insertOne() buffering timed out after 10000ms
at Timeout. (C:\Users\dahiy\OneDrive\Desktop\bots\omni-games\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
This issue normally is caused because:
wrong auth, by the meaning the mongo path string is wrong so maybe double check your pass and username
check the allowed IP to access the database from the mongo website, if you want it to be accessed from everywhere just use IP: 0.0.0.0/0
Your internet connection might be slow to the point it cannot connect to the DB
Hope you found this helpful! :)
You can open https://cloud.mongodb.com/
Click connect Goto the Connect your application
Select Driver Node.js version 4.1 leter
Copy the link which you have to show than paste this link to your
project .env file now try to run application connect Database and
check.

Error connecting to Atlas Free Cluster (MongoDB)

TL;DR: Can't connect to Atlas Cluster even after doing exactly what docs said.
Hi, so I read the docs of getting started with Atlas and everything seemed nice & easy. I did follow the steps, created a free cluster, whitelisted my IP, and then tried to connect using their sample app:
const { MongoClient } = require("mongodb");
// Replace the following with your Atlas connection string
const url = "mongodb+srv://<username>:<password>#clustername.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true";
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
} catch (err) {
console.log(err.stack);
}
finally {
await client.close();
}
}
run().catch(console.dir);
But the following error occurred when I tried to execute with: node connect.js
PS C:\Users\marjo\Documents\mongoDB Atlas> node connect
(node:11352) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [remote-doc-shard-00-02-otc5a.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:46:25
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
at Connection.emit (events.js:315:20)
at processMessage (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:384:10)
at TLSSocket.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connection.js:553:15)
at TLSSocket.emit (events.js:315:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}]
at Pool.<anonymous> (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\topologies\server.js:438:11)
at Pool.emit (events.js:315:20)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:561:14
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\pool.js:1008:9
at callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:97:5)
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:396:21
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\auth_provider.js:66:11
at C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\auth\scram.js:240:11
at _callback (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:349:5)
at Connection.messageHandler (C:\Users\marjo\Documents\mongoDB Atlas\node_modules\mongodb\lib\core\connection\connect.js:378:5)
I tried changing the connection string with the one from Atlas: (because it was different from the docs by a tiny bit)
const uri = "mongodb+srv://Marjo:<password>#remote-doc-otc5a.mongodb.net/<dbname>?retryWrites=true&w=majority";
But still the same result. My password had a !character so I put %21 instead of it. I also replaced with cluster name (Remote-Doc) and test but it still failed.
I'd appreciate if you could help me!
I think that you are having a problem with the parse of your password, maybe it has special characters.
The best way to handle this is to change the way that you are connecting to pass the user and password as options.
You can follow the doc and change your MongoClient conection for something like this:
const mongoclient = new MongoClient(new Server("remote-doc-otc5a.mongodb.net", 27017));
// Listen for when the mongoclient is connected
mongoclient.open(function (err, mongoclient) {
// Then select a database
const db = mongoclient.db("dbname");
// Then you can authorize your self
db.authenticate('username', 'password', (err, result) => {
// On authorized result=true
// Not authorized result=false
// If authorized you can use the database in the db variable
});
});
And with mongoose you can do something like this:
mongoose.connect('mongodb+srv://#remote-doc-otc5a.mongodb.net/test?retryWrites=true&w=majority', {
user: 'USERNAME',
pass: 'PASSWORD',
useNewUrlParser: true,
useUnifiedTopology: true
})
Also, check if you are not using the account password instead of the cluster/database password.
You can follow this tutorial to check if you are using the correct one: MongoDB Atlas Setup - Digital Ocean.
I just changed the Atlas password to a simple one with no special characters, and the connection worked! I feel ashamed now

Resources