What does mongodb is not a function mean? - javascript

I'm new to programming, I'm trying to follow a web developemnt course when connecting to database I created I get the error "mongodb.connect is not a function".
I try to connect to the database using the following code.
let mongodb = require('mongodb');
let db
let connectionString = '';
mongodb.connect(connectionString,{useNewUrlParser: true, useUnifiedTopology:
true},function(err, client){
db = client.db();

You can connect to the database from the client (which uses MongoClient from the library).
const { MongoClient } = require('mongodb');
let db;
const connectionString = 'mongodb://' // Change this to your uri
const client = new MongoClient(connectionString)
Then you can connect
await client.connect();
db = client.db();

Try this:
const { MongoClient } = require("mongodb");
let databaseName = '';
let connectionString = '';
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
if (error)
return console.log("Connection failed for some reason");
const db = client.db(databaseName);
});

just try this one
let mongodb = require('mongodb').MongoClient;
this could be for the version of mongodb you are using instead of version used in the course.

Related

No error message connecting to Mongo atlas database

I'm trying to connect to a Mongodb database. But I'm getting no errors just out put as far as,
console.log("001");
dotenv = require('dotenv');
dotenv.config();
const mongodb = require('mongodb').MongoClient;
const { MongoClient } = require("mongodb");
console.log("002");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
console.log("003");
async function run() {
try{
console.log("004");
client.connect();
//const db = client.db("blah");
console.log("005");
const results = await db.collection("student").find()
console.log("006")
console.log(results)
console.log("007")
client.close()
console.log("hello");
}
catch
{
}
}
//call function
run();
console.log("005");
But not,
console.log("006");
So there must be a problem with line 20,
const results = await db.collection("student").find()
Is the syntax correct here?
Not getting an error and yet it doesn't read any information from the database.
shane#XPS:~/mongostack$ node index.js
001
002
003
004
005
Thanks,

Why do I get mongodb.Connect is not a function when connecting to mongodb using node?

I want to connect to a mongodb database at cloud.mongodb.com using node.
I get the error mongodb.Connect is not a function. What am I doing wrong here?
const dotenv = require("dotenv");
dotenv.config();
const mongodb = require("mongodb");
const connectString = "my connection string";
mongodb.Connect(process.env.CONNECTIONSTRING, async function (err, client) {
const db = client.db();
const results = await db.collection("pets").find().toArray();
console.log(results);
});
JavaScript is case-sensitive. The function is connect, with a lower-case "c":
mongodb.connect(process.env.CONNECTIONSTRING, async function (err, client) {
// ---^
const db = client.db();
const results = await db.collection("pets").find().toArray();
console.log(results);
});
I believe this is due to one or both of these reasons:
You should import MongoClient and not the entire mongodb module
const { MongoClient } = require("mongodb");
The method name is connect and not Connect

Unable to connect to my database from my node js application

I've been trying to connect my application to my database, but it has not been possible. I've tried this below, and it still did not recognize my models
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = process.env.MONGODB_URL;
// Database Name
const dbName = 'KaydeeAcedemy';
// Use connect method to connect to the server
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
I've also tried using this connection string, yet no headway.
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URL;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
when I try to add a new user from my application, i get this error as a result of the database.
Operation `users.findOne()` buffering timed out after 10000ms
the mongodb url looks like this:
MONGODB_URL = mongodb+srv://Kaydeeacademy:**************#cluster0.ehclf.mongodb.net/KaydeeAcademy?retryWrites=true&w=majority
I don't know if I missed something in the connection string or somewhere.
Can you test/compare out some of my code (working)
// have you called in the dot.env file?
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
// don't include the "useNewUrlParser: true, useUnifiedTopology: true" see answer below:
// https://stackoverflow.com/questions/68915722/option-usefindandmodify-is-not-supported
// make sure there are no spaces in the dot.env file
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log("db connected!"))
.catch(err => console.error("db connection failed ", err))

MongoDB client in Node

Im trying to connect mongodb in node.js and take the link to client to the outer variable.
I need to create a module that would return a result of .find() method. How can i do this?
const MongoClient = require('mongodb').MongoClient
let client
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
mongoClient.connect((err, db) => {
if (err) {
return console.log(err)
}
client = db
})
const database = client.db('db')
const collection = database.collection('collection')
client.close()
And the error
const database = client.db('db')
^
TypeError: Cannot read property 'db' of undefined
As the comment suggests, you can use async/await to wait for the connection to be established, and do the error handling with a try/catch statement:
try {
const client = await mongoClient.connect()
const database = client.db('db')
const collection = database.collection('collection')
} catch(e) {
console.log(e)
}
Don't forget to use it in an async function.
Update
An async function example, you may want to return the collection:
const getData = async () => {
try {
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
const client = await mongoClient.connect()
const database = client.db('db')
const collection = database.collection('collection')
client.close()
return collection
} catch(e) {
console.log(e)
}
}
after uri you must define db name
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
like this
mongoClient = new MongoClient('mongodb://localhost:27017/shop', {useUnifiedTopology: true, useNewUrlParser: true})

TypeError: Cannot read property 'db' of undefined while trying to Mongodb Atlas Online

[nodemon] starting node server.js
C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:725
throw error;
^
TypeError: Cannot read property 'db' of undefined
at C:\Users\Abhay\Desktop\todo-app\server.js:8:17
at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:722:9
at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\mongo_client.js:223:23
at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\operations\connect.js:279:21
at QueryReqWrap.callback (C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\core\uri_parser.js:56:21)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:10)
[nodemon] app crashed - waiting for file changes before starting...
let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db
let connectionString = 'mongodb+srv://todoAppUser:kTL7PYesKzfB6FMz#cluster0.fif5n.mongodb.net/TodoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
db = client.db()
app.listen(3000)
})
It seems you're trying to use the static connect method of MongoClient to make a connection to your db, but you are not using the MongoClient class itself.
To connect to any db, you will need a connected instance of MongoClient. Using the static connect method, you can achieve it in the following way:
const mongodb = require("mongodb");
const connectionURL = "mongodb+srv://your-connection-srv-here"
const dbName = "your_db_name"
//get MongoClient
const MongoClient = mongodb.MongoClient;
let db = null;
MongoClient.connect(connectionURL,{
useNewUrlParser: true,
useUnifiedTopology: true
},(err,connectedClient) => {
if(err){
throw err;
}
//connectedClient will be the connected instance of MongoClient
db = connectedClient.db(dbName);
//now you can write queries
db.collection("your_collection").find({}).toArray()
.then(r => {
console.log(r);
}).catch(e => {
console.error(`ERROR:`,e);
})
})
However, using callbacks will be quite cumbersome. As per the docs linked above, most functions in the MongoDb driver for Node.js will return a promise if a callback function is not passed, which is very convenient. Using this, you can write a function which return a promise that resolves a connected instance to your db.
const MongoClient = require('mongodb').MongoClient;
/*
we draw the connection srv and the db name from the config to return just one instance of that db.
Now this function call be called wherever a connection is needed
*/
const getDbInstance = (config) => new Promise((resolve,reject) => {
const client = new MongoClient(config.dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
});
client.connect((error) => {
if(error){
console.error(error);
reject(error);
}
let db = client.db(config.dbName);
resolve(db);
})
})
const doSomeDbOperations = async() => {
//hardcoding it here, but this config will probably come from environment variables in your project
const config = {
dbUrl: "mongodb+srv://your-connection-srv-here",
dbName: "your_db_name"
};
try{
const db = await getDbInstance(config);
//do whatever querying you wish here
}catch(e){
console.error(`ERROR: `,e);
}
}
doSomeDbOperations();

Categories

Resources