(node:15976) UnhandledPromiseRejectionWarning when trying to connect to mongodb - reactjs

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

Related

Why React app cannot connect to Local mongodb using Localhost while success in 127.0.0.1

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.

Mongoose.connect() is not working and connecting

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;

Mongoose NextJS OverwriteModelError: Cannot overwrite `Note` model once compiled

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

React query mutation: getting the response from the server with onError callback when the API call fails

I am working on a React JS project. In my project, I am using React query, https://react-query.tanstack.com/docs/guides/mutations. I am using mutation to make the post request to the server. But I am trying the get the response returns from the server when the API call fails with the onError call back.
This is my code.
let [ createItem ] = useMutation(payload => createItem(payload), {
onSuccess: (response) => {
},
onError: (error) => {
// here I am trying to get the response. In axios, we can do something like error.data.server_error_code
},
onMutate: () => {
}
})
As you can see in the comment, I am trying to read a field returned from the server within the onError callback. How can I do that?
let [ createItem ] = useMutation(payload => createItem(payload), {
onSuccess: (response) => {
},
onError: (error) => {
console.log(error.response.data);
console.log(error.response.status);
},
onMutate: () => {
}
})
It's not entirely clear when just doing console.log(error) inside onError, but error.response should be available.
It should work as it is. Make sure that your HTTP client (probably, Axios) is configured to throw an error. For example:
import axios from 'axios'
import { useMutation } from 'react-query'
import { BASE_URL } from 'constants/api'
const client = axios.create({
baseURL: BASE_URL,
})
const request = (options) => {
const onSuccess = (response) => response
const onError = (error) => {
// Throwing an error here
throw error
}
return client(options).then(onSuccess).catch(onError)
}
const { mutate } = useMutation(
async (data) =>
await request({
url: '/someUrl',
method: 'post',
data
}),
{ onError: (e) => console.log(e) }
)
And of course, it's better to store your Axios settings within a separate file, and then just import the 'request' variable where mutations are using.
If you are using fetch, you have to know that fetch does not throw any error unless is a network problem (as read here)
My solution was just to change to axios (which throws error when 400 or 500), but if you still need to use fetch, you need to find a way to make it throw errors instead.
I think the issue with NOT having an error.response in the callback depends on how the API is failing. If you look at the react-query documentation it shows that most HTTP libs like axios will throw if there is a non 2xx response. However it's up to the underlying API function how it handles that.
For example axios https://axios-http.com/docs/handling_errors will return the response object if there is a response from the server. They will return the request if the call has timed out and return just a message if the previous two don't fit the error
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
However, if you're using the Fetch API you have handle this yourself. Taken straight from react-query's docs: https://react-query.tanstack.com/guides/query-functions#usage-with-fetch-and-other-clients-that-do-not-throw-by-default
useQuery(['todos', todoId], async () => {
const response = await fetch('/todos/' + todoId)
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
})

Pushing data from React in array in MongoDB

I want to push a string in an array in a MongoDB document using React/NodeJS/MongoDB,
Here's my code in React
async function toggleLike() {
try {
const dataUser = await axios.post(
`http://localhost:5000/user/${props.auth.user.id}/add/moviesLiked/${props.match.params.id}`);
console.log("user ", dataUser);
forceUpdate();
} catch (error) {
console.log(error);
}
Here's my code in NodeJS
router.post("/user/:user/add/moviesLiked/:movie", function(req, res) {
console.log("in api function add");
mongo.connect(
url,
{
useNewUrlParser: true,
useUnifiedTopology: true
},
(err, client) => {
if (err) {
console.error(err);
return;
}
const db = client.db("ofilms-demo");
const collection = db.collection("users");
collection.update(
{ _id: req.params.user },
{ $addToSet: { moviesLiked: req.params.movie } }
);
console.log("req params user ", req.params.user);
console.log("req params movie ", req.params.movie);
client.close();
}
);
});
Here's the model of an user in Mongoose
const UserSchema = new Schema({
moviesLiked: Array,
moviesDisliked: Array,
});
All my console.log show the right thing, but I still don't have the data pushed in the array,
Can somebody help me ? Thank you,
collection.update is asynchronous, so you need to wait for it to finish executing before closing your connection to Mongo and returning a response to the client.
You can wait for the update operation to complete by either passing a call back to the update method or using the async/await javascript feature.
Passing a call back function:
router.post("/user/:user/add/moviesLiked/:movie", function (req, res) {
mongo.connect(
url,
{
useNewUrlParser: true,
useUnifiedTopology: true
},
(err, client) => {
if (err) {
console.error(err);
return;
}
const db = client.db("ofilms-demo");
const collection = db.collection("users");
collection.update(
{ _id: req.params.user },
{ $addToSet: { moviesLiked: req.params.movie } },
function (error, result) { // The callback function
if (error) {
// Handle the error and send a respone to the user
} else {
// Make use of the result and send a response to the user
}
client.close();
}
);
}
);
});
Using async/await:
// Add the async keyword before declaring the function
router.post("/user/:user/add/moviesLiked/:movie", async function (req, res) {
mongo.connect(
url,
{
useNewUrlParser: true,
useUnifiedTopology: true
},
(err, client) => {
if (err) {
console.error(err);
return;
}
const db = client.db("ofilms-demo");
const collection = db.collection("users");
try {
// Add the await keyword before the update call
await collection.update(
{ _id: req.params.user },
{ $addToSet: { moviesLiked: req.params.movie } },
);
// Send response to your client
} catch (err) {
// Handle any possible error
}
client.close();
console.log("req params user ", req.params.user);
console.log("req params movie ", req.params.movie);
}
);
});
After DB i/o operation is done you should send back the response to your client something like this:
use try-catch to get the error message without crashing the whole node server.
Don't forget to send back the response to client otherwise, the client-side will keep waiting for server response until it's timeout reached
Node.js
router.post("/user/:user/add/moviesLiked/:movie", async (req, res) =>{
console.log("in api function add");
mongo.connect(
url,
{
useNewUrlParser: true,
useUnifiedTopology: true
},
(err, client) => {
if (err) {
console.error(err);
res.status(500).send({"message":"error occured", err})
return;
}
try{
const db = client.db("ofilms-demo");
const collection = db.collection("users");
const response = await collection.update(
{ _id: req.params.user },
{ $addToSet: { moviesLiked: req.params.movie } }
);
console.log("req params user ", req.params.user);
console.log("req params movie ", req.params.movie);
//send back the response
res.status(200).send({response, "message":"your profile is successfully updated."})
client.close();
}catch(err){
//check what is the error in your Nodejs console (Not browser console)
console.log(err)
//send back response
res.status(500).send({"message":"error occured", err})
}
);
}
});
MongoDB is itself schema-less. you don't have to provide schema. if you want to provide your own schema I'd recommend using mongoose. & mongoose arrays

Resources