I've tried to connect to mongodb with node.js, but get the following error. Although I've tried several available solution in this platform, like, changing my DNS to Google's Public DNS, downgrading the node.js driver's version for connection string, but they did not work out for me.
Error: queryTxt ETIMEOUT cluster0.1moqz.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:213:19) {
errno: 'ETIMEOUT',
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'cluster0.1moqz.mongodb.net'
}
here is my server side code:
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.1moqz.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
async function run() {
try {
await client.connect();
const userCollection = client.db('myTestDB').collection('users');
const newUser = { name: "username", email: "abc#def.com" };
const result = await userCollection.insertOne(newUser);
console.log("adding new user", result);
}
finally {
await client.close();
}
}
run().catch(console.dir);
Have you added you IP address to the IP Access List?
You must add your IP to the access list in order to access the database (from that IP). To do this:
Go to your MongoDB Atlas page
In the sidebar, under "Security" select "Network access"
Select the "IP Access List" tab
Click the "ADD IP ADDRESS" button
Enter your IP address (there should be a button that does this for you) and click "Confirm"
You should be able to access your MongoDB database after a minute or so
Related
I am new to mongoDB and nodejs i created a simple database and tried to connected to my nodejs but i get this error
**MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\Solutions\Desktop\MongoDB\node_modules\mongodb\lib\sdam\topology.js:312:38)
at listOnTimeout (node:internal/timers:568:17)
at processTimers (node:internal/timers:510:7) {
reason: TopologyDescription {
type: 'Unknown', **
MongoDB is running in my pc i can type mongodb commands i checked in task manager it is running everything looks fine but i can not connect it
this is my nodejs code
const url= 'mongodb://localhost:27017';
const databaseName='e-comm'
const client= new MongoClient(url);
async function getData()
{
let result = await client.connect();
db = result.db(databaseName);
collection = db.collection('products');
let data = await collection.find({}).toArray();
console.log(data)
}
getData();```
you need to add const { MongoClient } = require('mongodb'); in your code and also pass {useUnifiedTopology: true,useNewUrlParser: true} in MongoClient Constructure after url parameter as a best practice
I'm trying to connect a Node.js application with MongoDB Atlas trough Mongoose and I'm getting the following error:
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the
database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
at NativeConnection.Connection.openUri (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\index.js:332:10
at C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\index.js:1153:10)
at Mongoose.connect (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\node_modules\mongoose\lib\index.js:331:20)
at connectDb (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\src\connection.js:9:6)
at Server.<anonymous> (C:\Users\marin\Downloads\Project part2\Project part2\docker_app\server.js:27:3)
at Object.onceWrapper (events.js:519:28) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'cluster0.huaic.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
My code is:
const mongoose = require("mongoose");
const User = require("./User.model");
const connection = '"mongodb://cluster0.huaic.mongodb.net/myFirstDatabase"';
const connectDb = () => {
return mongoose
.connect(connection)
.then((res) => {
return res;
})
.catch((error) => {
console.log(error);
});
};
module.exports = connectDb;
I've allowed access from every IP on mongodb atlas and when I try to connect directly to atlas everything works fine.
For first, you have double quotes in the connection variable. Secondly: it seems to me that mongoUri should include the username and password in the query string, right?
Make sure your connection string is like below. It should include your username and password:
"mongodb+srv://username:password#cluster0.huaic.mongodb.net/yourdatabasename?retryWrites=true&w=majority"
Set up a user that has that password and that username by going to Database Access in your atlas account.
I am in need of assistance in terms of generating a request to my Microsoft SQL Server via a web service (Built in Node.js).
To summarize the problem at hand, it is as follows: I am currently logging into a MS Sql Server Management with a windows auth account - that is all find and dandy however, I am now trying to build a web service that allows for selects and transacts of some tables which is where I am running into issues now specifically in terms of logging in and pulling data to the web service.
Code
var express = require('express'); var app = express();
app.get('/',function(req,res) {
const sql = require('mssql');
// Connection Path
const myServerPath = String("xxxx\\WS1SQLEXPRESS");
// Connection String Parameter
const config = {
// User Login Details - Windows Auth or General User Account
user : 'xxxx-xxx\\AdrianH',
password: 'xxxxxx',
// Server path to connect to
server : myServerPath,
// Database
datebase: 'plex',
options : {
trustedConnection: true
}
};
sql.connect(config,function(err) {
if (err) console.log(err);
// Create Request Object
var request = new sql.Request();
// Query the Database
request.query('USE plex; SELECT * FROM [plex].[dbo].[tblWorkCenters]',function(err,recordset) {
if (err) console.log(err)
// send records as response
res.send(recordset);
});
});
});
// Start Server and listen on //http://localhost:8001/
var server = app.listen(3213,function(){
console.log('Server is running...');
});
I have hid sensitive information, here is the error code
{ ConnectionError: Login failed for user ''.
at Connection.tedious.once.err (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:244:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.processLogin7Response (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1397:14)
at Connection.message (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1932:14)
at Connection.dispatchEvent (C:\Users\adrianh\node_modules\tedious\lib\connection.js:1084:36)
at MessageIO.messageIo.on (C:\Users\adrianh\node_modules\tedious\lib\connection.js:984:14)
at MessageIO.emit (events.js:198:13)
at Message.message.on (C:\Users\adrianh\node_modules\tedious\lib\message-io.js:32:14)
at Message.emit (events.js:203:15)
code: 'ELOGIN',
originalError:
{ ConnectionError: Login failed for user ''.
at ConnectionError (C:\Users\adrianh\node_modules\tedious\lib\errors.js:13:12)
at Parser.tokenStreamParser.on.token (C:\Users\adrianh\node_modules\tedious\lib\connection.js:735:29)
at Parser.emit (events.js:198:13)
at Parser.parser.on.token (C:\Users\adrianh\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at Parser.emit (events.js:198:13)
at addChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:297:12)
at readableAddChunk (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:279:11)
at Parser.Readable.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_readable.js:240:10)
at Parser.Transform.push (C:\Users\adrianh\node_modules\readable-stream\lib\_stream_transform.js:139:32)
at doneParsing (C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1399:37)
at Request._query (C:\Users\adrianh\node_modules\mssql\lib\tedious.js:546:11)
at Request.query (C:\Users\adrianh\node_modules\mssql\lib\base.js:1335:12)
at C:\Users\adrianh\Desktop\JEC_Current_Projects\WebService\WCWebServiceIOS.js:30:13
at _poolCreate.then.catch.err (C:\Users\adrianh\node_modules\mssql\lib\base.js:287:7)
at process._tickCallback (internal/process/next_tick.js:68:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
** An interesting note to make is in --
(C:\Users\adrianh\node_modules\tedious\lib\token\stream-parser.js:80:14) message: 'Login failed for user \'\'.', code: 'ELOGIN' },
name: 'ConnectionError' }
It doesn't actually seem to pass my login information - any help will be greatly appreciated thank you.
If you are trying to connect mssql via windows authentication in node JS use this module.
var mssql = require('mssql/msnodesqlv8
Sample:
var mssql = require('mssql/msnodesqlv8')
var dbConfig = {
server: 'server',
driver: 'msnodesqlv8',
database: 'DBDATA',
port: '1433',
options: {
trustedConnection: true,
debug: {
packet: false,
payload: false,
token: false,
data: false
},
}
};
I'm using Node.js to connect to my PostgreSQL database.
I'm changing the way I create the connection to my PostgreSQL database in order to specify the maximum number of connections.
This is the existing piece of code (I've replaced the actual user/password with user and password; the db name is the same as the user):
// Load and initialize pg-promise:
const pgp = require('pg-promise')(initOptions);
let cn = process.env.DATABASE_URL_FULL
// Create the database instance:
const db = pgp(cn);
Where DATABASE_URL_FULL = postgres://user:password#manny.db.elephantsql.com:5432/user
This works fine. However, when I use this:
// Load and initialize pg-promise:
const pgp = require('pg-promise')(initOptions);
// Connection parameters
const cn = {
host: process.env.DATABASE_URL,
port: process.env.DATABASE_PORT,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
max: process.env.DATABASE_MAX_CON,
idleTimeoutMillis: process.env.DATABASE_IDLE_TIMEOUT
};
// Create the database instance:
const db = pgp(cn);
Where DATABASE_URL = manny.db.elephantsql.com.
I get this error:
Unhandled rejection Error: getaddrinfo ENOTFOUND postgres://manny.db.elephantsql.com postgres://manny.db.elephantsql.com:5432
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
Background
Making a small web app that connects to a Mongo DB hosted with Mlab. I've created the DB on mlab, and created users with read/write permission. I've also created a users collection with several records.
The Problem
When I try and connect to the database using the code on mongo.github.io, I hit the error:
/home/ed/dev/mongo-demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
throw err;
^
TypeError: Cannot read property 'db' of null
The Code
var MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://<user>:<pass>#ds115434.mlab.com:15434';
// Database Name
const dbName = 'princee3-music';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
What I Have Tried
Oddly, if I connect through the shell using:
mongo ds115434.mlab.com:15434/princee3-music -u <dbuser> -p <dbpassword>
That works fine, or if I wrap the connection in an anonymous self-calling async function, it also connects.
Async Wrapper
const MongoClient = require('mongodb').MongoClient;
const mongoUrl = 'mongodb://<user>:<pass>#ds115434.mlab.com:15434/';
const dbName = 'princee3-music';
(async() => {
const client = await MongoClient.connect(mongoUrl, { useNewUrlParser: true});
const db = client.db(dbName);
db.collection('users').insertOne({
email: user.email,
pass: hashedPassword,
admin: true
}, (err, result) => {
if (err) {
reject({error: err});
} else {
resolve({message: 'okay'});
}
});
client.close();
})();
Any pointers on where I may be going wrong would be great.
The official mLab docs advise to connect like below. It has to be asynchronous , in order to wait for the connection to occur, or the client will be null, thus throwing an error saying that it can’t read property db of null.
On the other hand, you async has useNewUrlParser which might be the key to have a successful connection, see this issue
MongoClient.connect(url, { useNewUrlParser: true }).then(client => client.db())