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

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

Related

MongooseError: Operation `users.insertOne()` buffering timed out

I am getting an error when trying to insert a document in the collection
MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
My dbLogic.js looks like this
const mongoose = require ("mongoose");
const User = require("./Collections/User")
mongoose.connect("mongodb://localhost:27017")
//console.log("Connected to db: ");
addUser()
async function addUser() {
const user = await User.create({ name: "Phiri", age: 40 })
console.log(user);
}
I also tried doing mongoose.connect("mongodb://localhost/myDatabase");
The connectionstring I am using mongodb://localhost:27017 is obtained from MongoDB compass. I am able to connect to the database using mongosh, and I can insert records etc.
My User.js looks like this
const mongoose = require ("mongoose");
const userSchema = mongoose.Schema({
name : String,
age : Number
})
module.exports = mongoose.model("User", userSchema);
The full errormessage I get
PS C:\Users\my_is\Programming\Project> node dbLogic.js
Listening on Port: 2000
(node:14400) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
C:\Users\my_is\Programming\Project\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:175
const err = new MongooseError(message);
^
MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Users\my_is\Programming\Project\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:175:23)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
I found this thread (among others), that didn't help me:
MongooseError: Operation users.insertOne() buffering timed out after 10000ms” in Mongo Db atlas
Ps. I am running locally.
Try mongoose.connect("mongodb://127.0.0.1:27017") instead of the mongoose.connect("mongodb://localhost:27017").
If connecting fails on your machine, try using 127.0.0.1 instead of localhost.
https://mongoosejs.com/docs/connections.html

MongoDB refusing to connect using NodeJS

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.

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.

Can Sequelize be used to connect to a new database?

In designing a simple node.js project, I tried using Sequelize to connect to a mysql server using the following configuration parameters:
{ dbname: users
username: jimmy
password: users
params:
host: localhost
port: 3306
dialect: mysql }
though the 'users' database didn't exist yet.
I got a server error:
InternalServerError: {"name":"SequelizeConnectionError","parent":{"code":"ER_BAD_DB_ERROR","errno":1049,"sqlState":"42000","sqlMessage":"Unknown database 'users'"},"original":{"code":"ER_BAD_DB_ERROR","errno":1049,"sqlState":"42000","sqlMessage":"Unknown database 'users'"}}
But the Sequelize docs: Manual | Sequelize indicate that Sequelize can connect to a new database. Please, how can Sequelize be used to connect to a
new(non-existing) database?
You should read the documentation again carefully (because the wording is indeed confusing!).
New databases versus existing databases
If you are starting a project from scratch, and your database does not exist yet, Sequelize
can be used since the beginning in order to automate the creation of
every table in your database.
Also, if you want to use Sequelize to connect to a database that is
already filled with tables and data, that works as well! Sequelize has
got you covered in both cases.
It will connect only to an existing DB, it can help you by creating the tables if they do not exist yet but the DB has to be there in order for sequelize to connect with it.
Following this question, I wrote this PR to update the documentation to be less confusing. Hope it help!
Found a similar problem on SO, and an answer by osifo:
//create the sequelize instance omitting the database-name arg
const sequelize = new Sequelize("", "<db_user>", "<db_password>", {
dialect: "<dialect>"
});
return sequelize.query("CREATE DATABASE `<database_name>`;").then(data
=> {
// code to run after successful creation.
});
So, I was able to implement it in my own code:
var SQUser;
var sequlz;
async function connectDB() {
sequlz =
new Sequelize("", "jimmy", "users", {host: "localhost", port: 3306, dialect: "mysql"});
await sequlz.query("CREATE DATABASE users;");
await sequlz.query("Use users;");
SQUser = sequlz.define('Table',
{
// define table schema
});
return SQUser.sync();
};
//use sequelize to populate the table
async function create() {
const SQUser = await connectDB();
return SQUser.create(
//values
);
}

Incomplete key value pair for option remote mongodb

I'm trying to deploy my local node mongoDB app to Heroku. Everything is working fine on my local machine, no errors.
First thing I'm trying to do is to connect to a database on mlab. It seen very straight forward but I get this error:
err { MongoParseError: Incomplete key value pair for option
name: 'MongoParseError',
message: 'Incomplete key value pair for option',
[Symbol(mongoErrorContextSymbol)]: {} }
My code looks like this:
var mongoose = require('mongoose');
const options = {
useNewUrlParser: true
};
mongoose.connect("mongodb://username:password#xxxxx.mlab.com:39251/nameodDB",options).then(
()=>{
console.log("connected to mongoDB")},
(err)=>{
console.log("err",err);
});
MongoDB password needs to be URLEncoded if it consists of special characters like "#" which highlights the start of the host

Resources