connect is not a function when connecting to mongodb - javascript

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

Related

MongoClient.connect not working in node.js

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/mydb'
MongoClient.connect(url, function(err,db) {
if (err) {
console.log("err")
} else {
console.log("Database Connected")
}
})
.connect is striked off in VS Code
err is displayed in the VS Code terminal
Node.js node-v18.12.0-x64
Mongodb version 4.2
windows 8.1 Pro
Sometimes it happens to me also. I don't use the connect function for now (macOS). Try this one:
const client = new MongoClient(uri);
const db = client.db('defaultDB');
and use it like:
await db.collection('movies').countDocuments();
Use this code. I had the same error and now it works (found this solution from this article on official mongoDb website).
MongoClient.connect('mongodb://0.0.0.0:27017',{ useNewUrlParser: true ,useUnifiedTopology:true},function(err,connect) {
if(err){
console.log("Error!")
} else {
console.log('Database connected.')
}
})

How can I stop getting the 'Can't resolve async_hooks' error when using npm start?

I've been following a tutorial on how to connect to a mongoDB collection. The tutorial works fine but I'm trying the same code in a project I'm working on and have been getting the following error constantly:
./node_modules/raw-body/index.js
Module not found: Can't resolve 'async_hooks' in '*:\*\*\Desktop\Projects\testing-area\node_modules\raw-body'
I've tried:
-deleting node_modules and then running npm install
-running npm update to bring all dependencies to the latest version
-updating npm itself
I've read that async_hooks is used for backend work and if you try to use it in the frontend, it can cause this issue. Problem is, I don't really know a way around it.
Here's the code I'm trying to use to connect to the mongodb collection:
//give functions of mongo db to MongoClient
const { MongoClient } = require('mongodb')
let dbConnection
const bark = (input) => {
console.log(input)
}
module.exports = {
connectToDb: (cb) => {
MongoClient.connect("mongodb://localhost:27017/Treasures")
.then((client) => {
dbConnection = client.db()
return cb()
})
.catch(err => {
bark("----------")
bark("Pants shat when trying to connect to DB:\n")
bark(err)
return cb(err)
bark("----------")
})
},
getDb: () => dbConnection
}
And then in a component I have this, to try and get the data from the collection:
// Imports/Requires for mongoDb connection
const { ObjectID } = require("bson");
const express = require("express");
const { connectToDb, getDb } = require("../../db")
// COMPONENT STARTS HERE:
export const TreasureGen = () => {
//init app and middleware
const app = express();
//db connection
let db
connectToDb((err) => {
if(!err)
{
app.listen(3000, () => {
bark("App listening on port 3000")
})
db = getDb()
}
})

Unresolved function or method connect() mongoose

I am learning Mongoose from JavaScript Everywhere book, and this is the code I had to write:
const mongoose = require('mongoose');
const mongoose = require('mongoose');
module.exports = {
connect: DB_HOST => {
mongoose.connect(DB_HOST);
mongoose.connection.on('error', err => {
console.error(err);
console.log('MongoDB connection error. Please make sure MongoDB is running.');
process.exit();
});
},
close: () => {
mongoose.connection.close();
}
}
when i hover over connect and connection, it shows Unresolved function or method connect() and Unresolved variable connection accordingly. My guess is that the book about an older version of mongoose, and in the newest version it is simply removed. What is the new function and variable for it?
Even though it's been some time.
replace your mongoose require with this:
const mongoose = require('mongoose').default;
should solve it for WebStorm
Still, I'd recommand using mongodb instead
I'm also learning Mongoose and have the same situation as you; here's how I fixed my error – you can use it as a reference to fix your code:
const {connect: connect1} = require('mongoose')
async function connect() {
try {
await connect1('DB_HOST')
console.log('\n Connected successfully')
} catch (err) {
console.log('\n Disconnect')
}
}
module.exports = { connect }

how to solve TypeError: Cannot read property 'connect' of undefined in mongodb?

I'm a trying to get database in my console
const mongoclient=require('mongodb').mongoclient
const state={
db:null
}
module.exports.connect=function(done){
const url='mongodb://localhost:27017'
const dbname='shopping'
mongoclient.connect(url,(err,data)=>{
if (err) return done (err)
state.db=data.db(dbname)
done()
})
}
module.exports.get=function(){
return state.db
}
and getting following error below
project-e-commerce#0.0.0 start C:\Users\krish\Desktop\project e commerce
> node ./bin/www
C:\Users\krish\Desktop\project e commerce\config\connection.js:11
mongoclient.connect(url,(err,data)=>{
^
TypeError: Cannot read property 'connect' of undefined
at Object.module.exports.connect (C:\Users\krish\Desktop\project e
commerce\config\connection.js:11:17)
at Object.<anonymous> (C:\Users\krish\Desktop\project e commerce\app.js:24:4)
Here is my code in app.js file
db.connect((err)=>{
if (err) console.log("connection error"+err);
else console.log("database connected to port 27017");
})
The error shows that you don't have mongoclient. Try installing it first.
npm i mongodb --save
Once, you have it get mongoclient.
const MongoClient = require('mongodb').MongoClient;
Then, try connecting the mongodb instance using it:
// Use connect method to connect to the server
MongoClient.connect(url, (err, client) => {
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});

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