MongoDB. connect() is not working what am I doing wrong? While trying to connect my mongoose to nodejs I got this error, importing part is okay and const connection with async and wait for the function is also okay, and try and catch, console log also shows a little bit of issue, I think useNewUrlParser,useUnifiedTopology part is wrong??
const Connection = async (username, password) => {
try {
const URL = `mongodb+srv://visco_blog:VISCOblog#123#blog.gttqj.mongodb.net/VISCO_BLOG?retryWrites=true&w=majority`;
await mongoose.connect(URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("Database connected successfully");
} catch (error) {
console.log("Error while connecting to the database ", error);
}
};
export default Connection;
Related
I am a starter of React. I am trying to connect React back-end app with local mongodb. I have imported MongoClient from mongodb. However, I cannot use app.get to get connect with local mongodb using following code:
app.get('/api/articles/:name', async (req, res) => {
try
{
const articleName = req.params.name;
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true});
const db = client.db('my-blog');
const articleInfo = await db.collection('articles').findOne({ name: articleName })
res.status(200).json(articleInfo);
client.close();
}
catch (error) {
res.status(500).json({'msg': 'Error connecting to db', error});
}
})
The error likes
{
"msg": "Error connecting to db",
"error": {
"reason": {
"type": "Unknown",
"servers": {},
"stale": false,
"compatible": true,
"heartbeatFrequencyMS": 10000,
"localThresholdMS": 15
}
}
}
However, it works when I edit the client command likes
const client = await MongoClient.connect('mongodb://127.0.0.1:27017', { useNewUrlParser: true});
What is the difference between using localhost and 127.0.0.1. Shouldn't these two same?
Thanks
I use Mongo 5.0.9
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
const client = await MongoClient.connect('mongodb://localhost:27017/MyDb', { useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,});
Try the above code.
in mongodb://localhost:27017/MyDb
I think you have to specify the DB name as well.
Hope this will be helpful to you.
I'm creating an application in Next.js and I'm at a stage where I need to load data from two different API endpoints that connect to MongoDB.
Specifically:
I have an index.js file that contains two components.
DashMenu.js (Component that displays basic information)
LunchMenuEditor.js (Component in which there is a textarea and the text of the lunch menu changes)
The problem occurs when I need to retrieve data from the address .../api/specials in the DashMenu component using useEffect() and at the same time the LunchMenuEditor component is loaded, which needs to retrieve data from the address .../api/[week].js?year=2022.
The result is an error: "MongoExpiredSessionError: Cannot use a session that has ended".
In my opinion there is an error in db.connect() and disconnect() in api files (see code). If I delete db.disconnect(), everything works, but the connection remains open.
I also tried db.connect() to insert it in setTimeout() with a wait of 3 seconds, it worked, but it occurs to me that it is not professional and I would be concerned about long-term sustainability.
So my questions are:
How to solve the problem "MongoExpiredSessionError: Cannot use a session that has ended"
Will it matter if the connection to MongoDB remains open? Does the connection end automatically after some time?
Thank you for every answer 🙂
Codes:
.../api/[week]:
import db from "../../../utils/db";
import LunchMenu from "../../../models/LunchMenu";
export default async (req, res) => {
await db.connect();
if (req.method === "GET") {
const lunchMenu = await LunchMenu.find({ week: 4, year: 2022 });
res.json(lunchMenu);
}
await db.disconnect();
};
.../api/specials:
import db from "../../../utils/db";
import Specials from "../../../models/Specials";
export default async (req, res) => {
await db.connect();
const specials = await Specials.find({ visible: true });
await db.disconnect();
res.json(specials);
};
utils/db.js
import mongoose from "mongoose";
const connection = {};
async function connect() {
if (connection.isConnected) {
console.log("Already connected.");
return;
}
if (mongoose.connection.length > 0) {
connection.isConnected = mongoose.connections[0].readyState;
if (connection.isConnected === 1) {
console.log("Uses previous connections.");
return;
}
await mongoose.disconnect();
}
const db = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("A new connection has been established.");
connection.isConnected = db.connections[0].readyState;
}
async function disconnect() {
if (connection.isConnected) {
await mongoose.disconnect();
connection.isConnected = false;
console.log("Disconnected.");
}
}
const db = { connect, disconnect };
export default db;
The code to connect to mongodb and why do I get an error on async.
And when I execute npm run start I get the following error
Please help ! Thank you.
use try catch to handle and avoid this warning of promise rejection
A way to resolve this is .
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(function(){
console.log('MongoDB Connected')
})
.catch(err => console.log(err));
To do this without callback use async await this way.
const connectDB = async () => {
try {
await mongoose.connect(`mongodb://${server}/${database}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
});
console.log('MongoDB connected!!');
} catch (err) {
console.log('Failed to connect to MongoDB', err);
}
I am learning to use Mongoose with NextJS and I keep running into this error. I have looked over similar questions but didn't figure out how to solve this. I have followed a tutorial video for implementing Mongoose step by step but in the video this problem didn't occur. Also, I hate to say it this inaccurately but it only happens "sometimes". Seems like every time I run the server first POST request always goes through, GET requests are also fine but when I try multiple POST requests it occurs. After restarting the server it works again. Here is my code:
import mongoose from "mongoose"
const connection = {}
async function dbConnect() {
if (connection.isConnected) {
retrun
}
const db = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
connection.isConnected = db.connections[0].readyState
console.log(connection.isConnected)
}
export default dbConnect
const mongoose = require("mongoose")
let NoteSchema = new mongoose.Schema({
email: {
type: String,
required: [true, "Please enter your email"]
}
})
module.exports = mongoose.model.Note || mongoose.model("Note", NoteSchema);
import dbConnect from "../../utils/dbConnect"
import Note from "../../models/Note"
dbConnect()
export default async (req, res) => {
const { method } = req
switch(method) {
case "GET":
try {
const notes = await Note.find({})
res.status(200).json({ success: true, data: notes })
} catch (error) {
res.status(400).json({ success: false })
}
break
case "POST":
try {
const note = await Note.create(req.body)
res.status(201).json({ success: true, data: note })
} catch (error) {
res.status(400).json({ success:false })
}
break
default:
res.status(400).json({ success:false })
break
}
}
Thanks for any help.
you should use mongoose.models.Note instead of mongoose.model.Note
so just try:
module.exports = mongoose.models.Note || mongoose.model("Note", NoteSchema);
This method is used to prevent overwrite model once compiled Mongoose
Please help I'm trying to deploy my app to App Engine/CloudSQL but I keep getting :
"UnhandledPromiserejectWarning": Cannot enqueue after fatal error..
I'm trying to query MySQL as promise, when I don't I handle the exception it works fine locally, but when I deploy it doesn't work.
How can I handle promise rejection, please Help Thanks
This is db.js
const db = require('./Mysql')
const query = (q, data) => {
return new Promise((resolve, reject) => {
db.query(q, data, (err, res) => (err ? reject(err) : resolve(res)))
})
.then(res => console.log(res))
.catch(err => console.error(err))
This is Mysql.js
{ SQL_SOCKET, SQL_USER, SQL_PASSWORD, SQL_DATABASE } = process.env
const db = mysql.createConnection({
socketPath: SQL_SOCKET,
user: SQL_USER,
password: SQL_PASSWORD,
database: SQL_DATABASE,
charset: 'utf8mb4',
})
module.exports = db
I remember having this problem a few years ago when I tried using the mysql module within an expressJS application and attempted to use async/await. The error could also come from querying on a connection in which a fatal error occured, see here. As such, best practices dictates that on queries, you open a connection, start a query transaction, commit the query and then release the connection afterwards -- allowing you to rollback whenever an error occurs. I do not see this process happening here so it could be a possibility.
In any case, I can provide you with an alternative, which is the method I ended up going with. Basically, I digressed promisifying query() myself and instead let node handle it.
An example of using query without transaction:
/backend/database/database.js
const mysql = require('mysql');
const db = require('../config/config').mysql;
const util = require('util');
const pool = mysql.createPool({
connectionLimit: require('../config/config').cLimit,
host: db.host,
user: db.user,
password: db.password,
database: db.database
});
pool.query = util.promisify(pool.query);
async function query(cmd) {
try {
let result = await pool.query(cmd);
return result;
} catch(error) {
console.error(error);
}
}
module.exports = {
query
};
Which can then be used in your models like such:
/backend/models/User.js
const db = require('../database/database');
async function getUserById(userId) {
const cmd = `SELECT * FROM Users WHERE userId = ${userId}`;
try {
let result = await db.query(cmd);
return result;
} catch(error) {
throw {
message: error
}
}
}
module.exports = {
getUserById
};
Which in turn, can be called from your route handler like such:
/backend/routes/users.js
const router = require('express').Router();
const User = require('../models/User');
router.get('/getUserById/:userId', async (req, res) => {
try {
let user = await User.getUserById(req.params.userId);
res.status(200).send({ user });
} catch(error) {
console.error(error);
res.status(400).send({ error: 'Unable to fetch user' });
}
});
module.exports = router;