why cant I connect mongodb to nodejs from localhost? - javascript

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

Related

Node.Js MSSQL Query Timeout Expired

I am using Node Express API to run SQL queries to populate a dashboard of data. I am using the mssql-node package to do so. Sometimes it runs flawlessly, other times I get the following error:
[Error: [Microsoft][SQL Server Native Client 11.0]Query timeout expired]
I am creating a poolPromise with a connectionPool to the db, then I pass that object to my other controllers which run the specific queries to populate data. I run the server which initiates the db.js script and connects to MSSQL with a pool connection.
db.js:
// for connecting to sql server
const sql = require('mssql/msnodesqlv8');
// db config to connect via windows auth
const dbConfig = {
driver: 'msnodesqlv8',
connectionString: 'Driver={SQL Server Native Client 11.0};Server={my_server};Database={my_db};Trusted_Connection={yes};',
pool: {
idleTimeoutMillis: 60000
}
};
// create a connectionpool object to pass to controllers
// this should keep a sql connection open indefinitely that we can query when the server is running
const poolPromise = new sql.ConnectionPool(dbConfig)
.connect()
.then(pool => {
console.log('Connected to MSSQL');
return pool;
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
module.exports = { sql, poolPromise };
An example of one of my controllers and how I use the poolPromise object is below. I currently have about 7 of these controllers that run their own specific query to populate a specific element on the dashboard. The performance of the queries each run within 1-10 seconds (depending on current server load, as I am querying an enterprise production server/db, this can vary). As I mentioned earlier, the queries run flawlessly sometimes and I have no issues, but at other times I do have issues. Is this a symptom of me querying from a shared production server? Is it preferred to query from a server that has less load? Or am I doing something in my code that could be improved?
const { sql, poolPromise } = require('../db');
// function to get data
const getData = async (req, res) => {
try {
// create query parameters from user request
let id= req.query.id;
// create query from connectionPool
let pool = await poolPromise;
let qry = `
select * from tbl where id = #Id
`
let data = await pool.request()
.input('Id', sql.VarChar(sql.MAX), id)
.query(qry);
// send 200 status and return records
res.status(200);
res.send(data.recordset);
} catch(err) {
console.log('Error:');
console.log(err);
res.sendStatus(500);
}
};
module.exports = { getData };

TypeError: Cannot read property 'execute' of undefined . node.js how to export oracle db connection

Hi I am new to node and oracle.I have created a app and made a successfull connection to db.
I need to use connection object across the application how can i do that?
Below is my index.js file
const express = require("express");
const app = express();
const authRoute = require("./routes/auth");
app.use(express.json());
app.use("/api",authRoute) ;
app.listen(3000,function(){
console.log("Node Server : Running on port 3000...");
})
database connection file => connect.js
const oracledb = require('oracledb');
const dotenv = require('dotenv');
dotenv.config();
const connection = oracledb.getConnection(
{
user : process.env.USER,
password : process.env.PASS,
connectString : process.env.ConnectString
},
function(err, connection)
{
if (err) {
console.error(err.message);
return;
}
console.log('Connection was successful!');
connection.close(function(err){
if (err) {
console.error(err.message);
return;
}
});
});
module.exports = connection;
I want to use this db connection in my auth.js file
const router = require('express').Router();
const db = require('../database/connect');
router.post("/authenticate",function(req,res){
//console.log(req);
const user = req.body.username;
const username = {"name" : user};
const pass = req.body.key;
const password = {"pass" : pass};
//const result = db.execute('select * from usertable');// this doesn't work
//console.log(result.rows);
res.send('success');
});
module.exports = router;
when i run const result = db.execute('select * from usertable'); I get the error below.
TypeError: Cannot read property 'execute' of undefined
What am i doing wrong.Can anyone please help.Thanks in advance
I had faced this problem. You must install Oracle install client v 19 in your machine. You have to go to web install oracle instant client base on your machine.
(Update: there is a multi-part series with code showing what you want at https://github.com/oracle/oracle-db-examples/tree/main/javascript/rest-api)
Use a connection pool that is opened at app start. Then the pool cache can be used to get the pool (and then connections) in other modules.
For a web app like yours you definitely want to use a connection pool for performance.
There's a big section on connection pooling in the documentation. E.g see Connection Pool Cache which says:
When pools are created, they can be given a named alias. The alias can
later be used to retrieve the related pool object for use. This
facilitates sharing pools across modules and simplifies getting
connections.
The examples are worth reviewing.

Node JS mssql exporting database connection

I have hard time understanding why my code doesn't work. I am using node package mssql and want to have database pool connection initiation in separate file:
databaseConnection.js:
const sql = require("mssql/msnodesqlv8");
config = {
database: process.env.DB_NAME,
server: process.env.DB_SERVER,
driver: "msnodesqlv8",
options: {
trustedConnection: true
}
};
let pool = sql.connect(config);
module.exports = pool;
Then I have my express route file data.js
const express = require("express");
const router = express.Router();
const db = require("../configs/databaseConnection");
router.get("/dataList", async (req, res) => {
let allData = await db.request().query("select * from dataList");
console.log(allData);
res.render("dataList", { title: "Data list" });
});
module.exports = router;
However, when I start the server and go to the route I get error:
(node:13760) UnhandledPromiseRejectionWarning: TypeError: db.request is not a function
The thing is if I setup precisely as this example mssql documentation (where verything would be done in the route) it works. However, if database connection is in separate file it doesn't work.
I would appreciate any help understanding this
Regards,
Rokas
sql.connect returns a promise, so once we know that, we can either do a .then(result => ... or use await, for example:
If you want to store the db object at startup for later I'd suggest changing the line:
const db = require("../configs/databaseConnection");
to
let db = null;
require("../configs/databaseConnection").then(pool => {
db = pool;
});

connect is not a function when connecting to mongodb

Error occurs when trying to run the function from the mongodb website that connects code to db.
const MongoClient = require('mongodb')
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Error is:
client.connect(err => {
^
TypeError: client.connect is not a function
I have mongodb installed via npm and uri defined as the string they gave. Do I need anything else?
The reason is that you should import the MongoClient class:
const MongoClient = require("mongodb").MongoClient;
Instead of the following line in your code: const MongoClient = require("mongodb");
Try connecting this way:
const { MongoClient } = require("mongodb");
const uri = "yourUri...";
const databaseName = "yourDBName";
MongoClient.connect(uri, { useNewUrlParser: true }, (error, client) => {
if (error) {
return console.log("Connection failed for some reason");
}
console.log("Connection established - All well");
const db = client.db(databaseName);
});
If you are using older version of MongoClient then try to install mongo client 2.2.33.
npm uninstall mongodb
npm install mongodb#2.2.33
If you are using the newer version (3.0 and above) of mongo client then modify the code as shown below.
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
if(err) throw err;
let db = client.db('test');
db.collection('devices').find().toArray(function(err, result){
if(err) throw err;
console.log(result);
client.close();
});
});
For that problem, the standard solution is to import clientPromise because versions higher than 3.9/4.0 do not have import {Mongoclient} command.
Then also, if you want to use MongoClient then,
Stop the current running server
Type npm i mongodb#3.5.9 in terminal
Restart your server by npm/yarn run dev
Now it will work
const mongodb = require('mongodb').MongoClient();

Failing to connect to MongoDB hosted on mlab

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())

Categories