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
Related
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.
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
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.
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
I have created a mongodb replica set in 3 virtualbox vms, manasger1, worker1, worker2. each replica set has it's own containers. The replica set works fine and I can login to the servers:
docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase "admin"'
MongoDB shell version v3.6.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.4
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
rs1:PRIMARY> use medmart_db
switched to db medmart_db
rs1:PRIMARY> db.providers.findObe()
2018-05-14T17:46:38.844+0000 E QUERY [thread1] TypeError: db.providers.findObe is not a function :
#(shell):1:1
rs1:PRIMARY> db.providers.findOne()
{
"_id" : ObjectId("56ddb50c230e405eafaf7781"),
"provider_id" : 6829973073,
When I run my nodejs application it connects to the replica set. The problem is that when I create a container for my application I get the following exception, my container stops, and I can no longer connect to the replica set PRIMARY, but instead to the secondary.
(node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [worker2:27017] on first connect [MongoNetworkError: connection 5 to worker2:27017 timed out]
at Pool.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:505:11)
at Pool.emit (events.js:182:13)
at Connection.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:329:12)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Socket.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:256:10)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at Socket._onTimeout (net.js:447:8)
at ontimeout (timers.js:427:11)
at tryOnTimeout (timers.js:289:5)
at listOnTimeout (timers.js:252:5)
at Timer.processTimers (timers.js:212:10)
(node:16) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I opened an issue ticket with mongoose for help but their solution doesn't work (they asked that I change from ip address to domain name but I still get the same error).
My connection module is:
'use strict';
const mongoose = require('mongoose');
const getURL = (options) => {
const url = options.servers.reduce((accumulator, current) => {
accumulator += current+',';
return accumulator;
},`mongodb://${options.user}:${options.pass}#`);
return `${url.substr(0,url.length-1)}/${options.db}?replicaSet=${options.repl}&authSource=admin`;
}
const connect = (config, mediator) => {
mediator.once('boot.ready', () => {
const options = {
native_parser: true,
poolSize: 5,
user: config.user,
pass: config.pass,
promiseLibrary: global.Promise,
autoIndex: false,
reconnectTries: 30,
reconnectInterval: 500,
bufferMaxEntries: 0,
connectWithNoPrimary: true ,
readPreference: 'ReadPreference.SECONDARY_PREFERRED',
};
mongoose.connect(getURL(config), options);
mongoose.connection.on('error', (err) => {
mediator.emit('db.error', err);
});
mongoose.connection.on('connected', () => {
mediator.emit('db.ready', mongoose);
});
});
};
module.exports = Object.assign({},{connect});
My config file is:
'use strict';
const serverConfig = {
port: 3000,
};
const dbConfig = {
db: 'xxxxxxx',
user: 'xxxxxx',
pass: 'xxxxxxx',
repl: 'rs1',
servers: (process.env.DB_SERVERS) ? process.env.DB_SERVERS.split(' ') : ['192.168.99.100:27017','192.168.99.101:27017','192.168.99.102:27017'],
};
module.exports = Object.assign({},{dbConfig, serverConfig});
So there are a couple of steps to resolving this issue. First and foremost is the fact that hosts file on the virtualBox machines must be updated to have the ip addresses of mongodb domains. To do that:
> docker-machine ssh manager1
docker#manager1:~$ sudo vi /etc/hosts
#add the following
192.168.99.100 manager1
192.168.99.101 worker1
192.168.99.102 worker2
Repeat for worker1 and worker2.
If by adding the following you are good, then skip the second part.
Next, if you get the following error:
Error: ERROR::providers-service::model::ProviderModel::getProviderById: TypeError: Cannot read property 'wireProtocolHandler' of null
at cb (/home/nupp/app/src/model/ProviderModel.js:182:13)
at /home/nupp/app/node_modules/mongoose/lib/model.js:4161:16
at Immediate.Query.base.findOne.call (/home/nupp/app/node_modules/mongoose/lib/query.js:1529:14)
at Immediate.<anonymous> (/home/nupp/app/node_modules/mquery/lib/utils.js:119:16)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)
Remove any options to mongoose.connect. Here's how mine looks now:
mediator.once('boot.ready', () => {
const options = {};
mongoose.connect(getURL(config), options);
mongoose.connection.on('error', (err) => {
mediator.emit('db.error', err);
});
mongoose.connection.on('connected', () => {
mediator.emit('db.ready', mongoose);
});
});
Hope my solution can help someone else. Took me a few long days to finally figure this out.