MongooseError: Operation 'featureds.find()` buffering timed out after 10000ms - javascript

I have a collection on MongoDB from which I'm trying to query all the elements using find():
const mongoose = require('mongoose');
const Featured = mongoose.model('featured');
module.exports = app => {
app.get('/api/featured', async (req, res) => {
console.log("featured route");
const featured = await Featured.find();
console.log(featured);
res.send(featured);
})
}
Here's Featured.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const featuredSchema = new Schema({});
mongoose.model('featured', featuredSchema);
However, I'm getting the error upon making the request:
(node:75568) UnhandledPromiseRejectionWarning: MongooseError: Operation `featureds.find()` buffering timed out after 10000ms
at Timeout.<anonymous> (/Users/prikshetsharma/Desktop/humboiserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(node:75568) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
How to fix this error and get all the collection items to return with find()? Strangely, the error shows featureds.find() whereas I've never used featureds word in my code anywhere.

For anyone else who might stumble upon this: My issue had to do with a faulty connection, and I managed to fix it by using mongoose.connect instead of mongoose.createConnection.
Please note the Mongoose documentation saying:
Mongoose will not throw any errors by default if you use a model without connecting.
...which just results in a buffering timeout instead.

if you are on localhost, using
mongoose.connect('mongodb://localhost:27017/myapp');
try using 127.0.0.1 instead of localhost
mongoose.connect('mongodb://127.0.0.1:27017/myapp');

Quick Fixes:
Export model in Featured.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const featuredSchema = new Schema({}, { collection: "featured" });
module.exports = mongoose.model('featured', featuredSchema);
UnhandledPromiseRejectionWarning: Unhandled promise rejection,
You need to wrap your service code in try catch block,
const mongoose = require('mongoose');
// correct this path to your original path of Featured.js
const Featured = require('./Featured.js');
app.get('/api/featured', async (req, res) => {
try {
console.log("featured route");
const featured = await Featured.find();
console.log(featured);
res.send(featured);
}
catch(e) {
console.log('Catch an error: ', e)
}
});
featureds.find() buffering timed out after 10000ms,
there would be many possibilities,
Remove the mongoose module from node_module and also from *.json files, reinstall mongoose module and try again.
Check if you have connected with database or not, after that check if you have the correct network access to your database cluster.

If anyone is using Mongo db Atlas then they need to whitelist their IP address to authorize the access.
Steps to authorize the access.
Get your systems IP address
For Mac User : Hit this command on terminal . curl ifconfig.me
For Windows user : Hit this command on command Prompts . ipconfig /all
You can find your IP Address by web also. eg. https://whatismyipaddress.com/
Once you have your networks IP address:
Go to Mongo DB Atlas -> Network Access -> IP Access List - Add your IP address. You can share access to specific IP address or you can keep open access for all as well.

Related

How can I fix TypeError: Cannot read properties of undefined (reading 'split') in mongoose?

I just connected mongoDB using mongoose.
But I got error TypeError: Cannot read properties of undefined (reading 'split')
How can I fix this error?
Here's my code
export const dbConnect = async () => {
mongoose.connect(process.env.NEXT_PUBLIC_MONGO_URI);
const db = mongoose.connection;
db.on('error', function () {
console.log('db connection failed!');
});
db.once('open', function () {
console.log('db connected!');
});
};
And I am using mongoose version 6.5.3, next version 12.2.5
If the error appears in the browser, it means that you are trying to use Mongoose in your client side code.
In fact, somewhere in its code, Mongoose checks for the version of the node installation it's using.
Being ran in the browser, there is no such thing as process.versions.node, hence the error.
What is value of process.env.NEXT_PUBLIC_MONGO_URI
Format should be like
mongoose.connect('mongodb://localhost/myapp');
mongoose.connect('mongodb://username:password#host:port/database?options...');
I think the problem will be in the connect function. The URI you give in might be wrong. Try logging it our before the function, to make sure it's a correct uri.
https://www.mongodb.com/docs/manual/reference/connection-string/
Here you can find the correct connection string format.
TL;DR
Use a dynamic import. instead of:
import mongoose from 'mongoose';
export const connectDb = async () => {
try {
await mongoose.connect('your-connection-string', { });
} catch (error) {
// exit process with failure
process.exit(1);
}
};
Try:
import dynamic from 'next/dynamic';
// import mongoose from 'mongoose';
export const connectDb = async () => {
try {
// Dynamically load mongoose
const mongoose = (await import('mongoose')).default;
await mongoose.connect('your-connection-string', { });
} catch (error) {
// exit process with failure
process.exit(1);
}
};
See the docs here: Dynamic Imports
Why does this work?
Luca was correct to say the following:
If the error appears in the browser, it means that you are trying to
use Mongoose in your client side code.
In fact, somewhere in its code, Mongoose checks for the version of the
node installation it's using.
To expand on that, node.js is not available on the client side of a next.js project, but it is available where server-side code runs such as getServerSideProps or /pages/api. I assume you only want to use this function inside the /pages/api folder and in that case it should work just fine.

Connecting code to MongoDB database gives error: Error: querySrv ENODATA _mongodb._tcp.cluster0.h5prp.mongodb.net

I'm coding a discord bot and I want to connect it to a mongoDB database. However when doing this, I get this error,
Error: querySrv ENODATA _mongodb._tcp.cluster0.h5prp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:228:19) {
errno: undefined,
code: 'ENODATA',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0.h5prp.mongodb.net'
}
Here is my code:
client.on('ready', () => {
console.log('The bot is ready!')
const dbOptions = {
// These are the default values
keepAlive: true
}
new WOKCommands(client, {
// The name of the local folder for your command files
commandsDir: path.join(__dirname, 'commands'),
// Allow importing of .ts files if you are using ts-node
typeScript: true,
// Pass in the new dbOptions
dbOptions,
// Pass in your own mongo connection URI
mongoUri: 'mongodb+srv://discordbot:******#cluster0.h5prp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
})
})
I looked through documentation and other posts but could not find anything that solves my problem.
I'm using Node.js v17.1.0. I'm using WOKCommands and following this tutorial series https://youtube.com/playlist?list=PLaxxQQak6D_f4Z5DtQo0b1McgjLVHmE8Q
I've allowed all IP Addresses to access my database, I've ensured my IP address is whitelisted
Any help appreciated.
Thanks
I needed to change the mongoDB connection URI to an earlier Node.js version.
I changed it to version '2.2.12 or later' and it worked.
Which game me a link like this:
mongodb://discordbot:<password>#cluster0-shard-00-00.h5prp.mongodb.net:27017,cluster0-shard-00-01.h5prp.mongodb.net:27017,cluster0-shard-00-02.h5prp.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-g86xz1-shard-0&authSource=admin&retryWrites=true&w=majority

MongoDB/Mongoose Connection Error when Dbname is used in the connection string

A NodeJS app uses mongoose 5.6.0 to connect to MongoDB 4.0.10 which runs on localhost inside a docker container.
The connection can be established when we use
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri)
Problem: We start getting authentication errors when we include the name of the database we are connecting to. There is no problem using Python to connect to the same MongoDB database.
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri)
and also tried
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri, { useNewUrlParser: true })
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Authentication failed.
Why is it unable to make the connection and how can we solve this problem?
Update
Found the solution to be
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri, { useNewUrlParser: true, dbName: 'my-db' })
Why must the dbname be passed as an option instead of including it in the connection string?
This has worked for me, thanks.
var result = await mongoose.connect('mongodb://root:example#localhost:27017/', {useNewUrlParser: true,dbName: 'my-db'})
Short answer: Add ?authSource=admin to URI string or use {authSource:"admin"}
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db?authSource=admin'
mongoose.connect(mongoUri)
Follow this answer https://stackoverflow.com/a/68137961/12280326 for detailed explanation.

UnhandledPromiseRejectionWarning Error: Slash in host identifier

I am trying to run nodemon index.js in my terminal but I am getting the following error which I have absolutely no idea what it means as for me is very unclear.
Can please anyone explain to me how to solve this?
index.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var app = express();
var router = require('./services/router');
mongoose.connect('mongodb://localhost:apiAuth');
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use('/v1', router);
var PORT = process.env.PORT || 3000;
var HOST = process.env.HOST || '127.0.0.1';
console.log('Listening on', HOST, PORT);
app.listen(PORT, HOST);
services/router.js
var router = require('express').Router();
function protected(req, res, next) {
res.send('Here is the secret!');
}
router.route('/protected')
.get(protected);
module.exports = router;
Terminal
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Listening on 127.0.0.1 3000
(node:29104) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Slash in host identifier
(node:29104) [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.
The problem comes from your connection to MongoDB via Mongoose.
Short version :
You have entered a bad login URL:
mongoose.connect('mongodb://localhost:apiAuth');
^^^^^^^
I think you want to write (or something close to it):
mongoose.connect('mongodb://localhost:'+apiAuth);
Here's an example of a MongoDB login URL : mongodb://127.0.0.1:27017/my_db.
Or the doc: Standard Connection String Format
Long version :
The resolution of the problem is the same as above, but you would have located it yourself.
For my part, I proceeded like that (because I had exactly the same problem, with as much information).
Isolate the code that generates the error: You can simply comment on parts of your code to determine which zone is crashing.
Add a catch() after the connection with Mongoose: mongoose.connect(...).catch((e) => { console.log(e); throw e; }. This will have indicated directly the line concerned and some additional information.
This kind of technique works in a lot of cases.
I also have same error as like above (Error: Slash in host identifier). I resolved the issue. I am accessing mongooses as like below. My database password contains # so here is the problem when our password having # special character we need to pass with the help of encodeURIComponent. I passed the user name and password as like below its working fine for me.
Error:
mongoose.connect('mongodb://xxx-xx:7a?VNXd##sabfpV8=gRLwnNvC_8#196.89.12.168:27017/xxxxx',function(err,db){
if(err){
console.log(err);
}else {
console.log('connected to the Test db');
}
});
Resolved code:
mongoose.connect('mongodb://xxx-xx:'+encodeURIComponent("7a?VNXd###safpV8=gRLwnNvC_8")+'#196.89.12.168:27017/xxxxx',function(err,db){
if(err){
console.log(err);
}else {
console.log('connected to the Test db');
}
});
I was facing similar error, what i did is
Previous Error Causing Version:
mongoose.connect("mongodb://localhost:cat_app");
Working Version
mongoose.connect("mongodb://localhost/cat_app");
Both are same except : is replaced with /

Getting error trying to create Postgres DB in Node.js

Im learning Node and trying create a server using Express and connecting it to a postgres db and keep getting the following when I run node server.js:
events.js:72
throw er; // Unhandled 'error' event
^
error: role "username" does not exist
at Connection.parseE (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:526:11)
at Connection.parseMessage (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:356:17)
at Socket.<anonymous> (/Users/rs/Desktop/Jobletics/node_modules/pg/lib/connection.js:105:22)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:764:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:426:10)
at emitReadable (_stream_readable.js:422:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
my server.js file looks like this:
// app dependencies
var express = require("express");
var Sequelize = require("sequelize");
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
//middleware
app.use(bodyParser());
app.use(morgan('dev'));
//sequalize initialization
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
var employerRoute = require("./routes/employer")(sequelize);
//sync the model with the database
sequelize.sync().success(function (err) {
app.get("/employer", employerRoute.get);
app.post("/employer", employerRoute.create);
app.listen(5000);
});
I have postgres running. Do I need to create a new db in the command-line then run $psql to create username/password? Shouldn't the db get created automatically?
You can use
var sequelize = new Sequelize("postgres://username:password#localhost:5432/jobletics");
for connecting to postgresql database, but sequelize does not create nor user nor database for you. You must do it yourself. Use createuser and createdb postgres utilities to create them, or user -c flag of psql command. You also must have privilege to do it, so in the next example commands run using postgres user:
su postgres -c "psql -U postgres -c \"CREATE USER username WITH ENCRYPTED PASSWORD 'password'\""
su postgres -c "psql -U postgres -c \"CREATE DATABASE jobletics WITH OWNER=username ENCODING='UTF8'\""
Although Sequelize does not have a method to create databases, you can use the create query method to execute a custom method.
But the catch is the following,
You need to "connect to a database" to execute any command
Here you can't do that because it's that database creation command that you would want to create in the first place.
There's one simple way to overcome this. Postgress has two inbuilt template DBs that cannot be dropped called template0 and template1 respectively. More on template databases here
So all you have to do is connect to template1 (not template0) in your connection string
const sequelize = new Sequelize('postgres://username:password#localhost:5432/template1')
and execute the sequelize query method with the create query command
const createQuery = "CREATE DATABASE YOUR_DB_NAME WITH OWNER = postgres ENCODING = 'UTF8' LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252' TABLESPACE = pg_default CONNECTION LIMIT = -1;"
sequelize.query(createQuery)
.then(() => console.log("DB created"))
.catch(err => console.log("error creating DB", err))
I have not seen the database getting created automatically. When I use sequelize.js, i normally run it within a vm which has a puppet manifest to assert that the database already exists.
Also, when it comes to connecting to the db, I would normally do it like so as I think it is easier to read:
var Sequelize = require("sequelize");
var sequelize = new Sequelize(
"dbName",
"username",
"password",
{
"dialect": "postgres",
"port": 5423
}
);
Finally, make sure that postgres existing in your package.json, if is doesn't you will have to run the following:
npm install --save pg pg-hstore

Categories