MongoAtlas Error: invalid schema, expected mongodb - node.js

I am trying to connect to MongoAtlas, however I keep getting
Error: invalid schema, expected mongodb
It seems to be that I can connect, but it cannot get my db from MongoAtlas. My try catch error returns me (node:5964) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined
.env
PORT = 9055
MONGO_URI =mongodb+srv://<my-db-username>:<my-password>#cluster0.vossd.mongodb.net/<db-name>?
retryWrites=true&w=majority
server.js
require('dotenv').config();
const port = Number.parseInt(process.env.PORT, 10);
const mongoUri = process.env.MONGO_URI;
const {MongoClient} = require('mongodb');
const express = require('express');
const Application = require('./application');
const application = Application();
const Health = require('./health');
const Product = require('./product');
const Cart = require('./cart');
const Order = require('./order');
async function main() {
let db;
try {
db = await MongoClient.connect(mongoUri);
console.log(db)
} catch (err) {
console.log(err);
}
application.use('/health', Health());
application.use('/product', Product(db));
application.use('/cart', Cart(db));
application.use('/order', Order(db));
const server = application.listen(port, () => {
const host = server.address().address;
const port = server.address().port;
console.log(`Shopping website server up and running, listening at http://${host}:${port}`);
});
}
main();
Everything works fine when I'm connected to my local db, so I'm unsure as to what I'm doing incorrectly. Any advice is much appreciated. Thank you!

This cannot read property 'collection' of undefined might be misleading as you have caught the error happening on connection. Hence db is null so if you access collection it will give this error. Below is the sample code from Mongo Atlas.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>#test.w7hgn.mongodb.net/<dbname>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true }); // <-- note the option
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});

Related

users.insertOne()` buffering timed out after 10000ms

I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (E:\e-commer backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:158:23)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
Node.js v18.12.1
db.js
const mongoose = require('mongoose');
const mongoURI = "mongodb+srv://wasif:kingofnoobs#cluster0.fmaocsf.mongodb.net/new"
// const server = 'mongodb://localhost:27017'
// const dbName = 'ecommerceBackend'
mongoose.set("strictQuery", false);
const connectToMongo = () => {
try {
mongoose.createConnection(mongoURI);
console.log("Connected");
} catch (error) {
console.log("Error In Connection");
}
}
module.exports = connectToMongo;
index.js
const connectToMongo = require('./db');
const express = require('express')
connectToMongo();
const app = express()
const port = 3000
app.use(express.json())
app.use(require('./routes/auth'))
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
auth.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();
const User = require('../models/User');
router.post('/api/auth', [
body('name').isLength({ min: 3 }),
body('email').isEmail(),
body('password').isLength({ min: 5 }),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const user = User(req.body);
user.save()
res.send(req.body);
})
module.exports = router
I have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this errorI have provided the whole code it's a simple code for the user's data to MongoDB database but it's not saving in MongoDB. and i can't find out where I am wrong, I have tried to async await the connection but still got this error
sorry, posting for the first time that's why

How to reference the connected mongo db routes in api routes in node js

i just started learning mongo db , i connected my database atlas successfully but i need to call the client variable in api routes when i do so it is saying client not connected
const express = require("express");
const res = require("express/lib/response");
const app = express()
const {MongoClient} = require("mongodb")
async function main(params) {
let uri = "mongodb+srv://usn:pwd#cluster0.tasg9.mongodb.net/movies?retryWrites=true&w=majority"
const client = new MongoClient(uri)
try{
await client.connect()
}catch(e){
console.log(e)
}
finally{
await client.close()
}
}
function ListDatabases(client) {
let databases = client.db().admin().listDatabases()
console.log("databases ->")
databases.databases.forEach(element => {
console.log(`--${element.name}`)
});
}
main()
app.get("/db", function (req, res) {
ListDatabases(client)
return res.json("db")
});
app.listen(8000,() => {
console.log("server running on port 8000")
})
how to reference the connected instance in api routes in the above code
You are closing the connection in finally block, so as soon as you are connecting, you are also disconnecting it right away.
Remove the finally block
finally {
await client.close()
}

Unable to connect to mongodb databse using node.js

I am unable to connect to mongodb from node.js using mongoose as database driver. Also I am getting the following error.
Error:
Error in DB connection:{"ok":0,"code":18,"codeName":"AuthenticationFailed","name":"MongoError"}
I am explaining my code below.
const mongoose = require('mongoose');
const dbUser = process.env.USERNAME || 'admin';
const dbPass = process.env.PASSWORD || 'admin';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;
console.log('url', url);
const options = {
useNewUrlParser: true,
useCreateIndex: true,
connectTimeoutMS: 5000000,
poolSize: 10000,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongoose.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection with mongoose successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
Here the database edqart-db is not actually present inside that particular mongo server. I need once one record will insert the db will created dynamically. If I have let dbName = 'admin'; then my node is connected to mongodb but for other db which is not created from beginning its showing error. I need once one record is going to insert then the db edqart-db will created. Here I just need the similar method like client.db(dbName) of require('mongodb').MongoClient for mongoose also.
I don't think its possible to authenticate on non existing db.
Here is what you should do if you want to enable auth on edqart-db.
Create a database edqart-db.
Create a user on that edqart-db. lets say username=edqartReadUser and password=edqartReasPassword.
Then your existing code should work below url.
const dbUser = process.env.USERNAME || 'edqartReadUser';
const dbPass = process.env.PASSWORD || 'edqartReasPassword';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;

Not Able to Connect to Password-protected MongoDB Server/DB

After successfully testing my Node app against a local mongoDB db, I am now trying to connect to our server db - which, unlike my local mongoDB, is user and password protected.
I am running into issues while trying the connection to the server. Specifically, I am getting this error:
MongoError: MongoClient must be connected before calling
MongoClient.prototype.db
The creds I'm trying look something like this:
{
"MONGO_URL": "mongodb://myuser:mypassword#someurl.com:27017?authSource=admin",
"MONGO_DATABASE": "bta",
"MONGO_COLLECTION": "jobs"
}
And here is my connection code:
const config = require('./configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);
async function getJobDetails() {
client.connect(async function () {
try {
const db = await client.db(dbName);
// do stuff
});
} catch (error) {
console.log(error);
}
});
}
What am I missing here?
I figured out what the issue was and was able to get it to connect. The issue was that the site is secure, so I had to add ssl=true to the url connection string:
const url = 'mongodb://user:password#someurl.com:27017/bta?ssl=true&authSource=admin';
try:
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(url, { useNewUrlParser: true }, function(client_err, client) {
if (client != null) {
var client_db = client.db(dbName);
}
client.close();
});
As MongoDB.
https://mongodb.github.io/node-mongodb-native/3.2/tutorials/connect/
And please Try double checking DB on the server if it has the right config.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL with password example
const url = 'mongodb://user:password#address:27017?readPreference=primary&authSource=admin';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
This works for both valid localhost/server url

TypeError: 'connect' only accepts a callback

when I try node index.js my error comes with TypeError: 'connect' only accepts a callback, then I'm confused about how to solve this problem.
The error goes to mongo_client.js:165:11
I did a tutorial about how to connect to mongodb with Nodejs but, I found a problem that ppl never had since now
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient();
const url = 'mongodb://localhost:27107/testedmtdev';
MongoClient.connect(url, function(err, client){
if(err){
console.log('Unable to connect to the Mongodb server. Error : ', err);
} else {
app.listen(3000, ()=>{
console.log('Connected to mongodb, webservice running on port 3000');
})
}
});
I expect the output of 'Connected to mongodb, webservice running on port 3000'
It's because you're actually calling MongoClient with no parameters.
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient(); // <-- your calling the method here
Make a change to just use a reference
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient; // <-- do *not* call method
https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect

Resources