I have been learninng NodeJS and mongoDB by youtube, but unfortunately i faced with this problem, and here is my code file! thank you in advance!
db.js
const { MongoClient } = require("mongodb");
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect("mongodb://localhost:27017/bookstore")
.then((res) => {
dbConnection = res.db();
return cb();
})
.catch((error) => {
console.log(error);
return cb(error);
});
},
getDb: () => dbConnection,
};
index.js
const express = require("express");
const { connectToDb, getDb } = require("./db");
// init app and middleware
const app = express();
//db connection
let db;
connectToDb((xato) => {
if (!xato) {
app.listen(3000, () => {
console.log("The 3000 port is installed");
});
db = getDb();
return db;
}
});
//routes
app.get("/bookstore", (req, res) => {
let mybook = [];
// the collection name from mongoDB
db.collection("bookstore")
.find()
.sort({ author: 1 })
.forEach((book) => mybook.push(book))
.then(() => {
return res.sendStatus(200).json(mybook);
})
.catch(() => {
return res.sendStatus(500).send("there were an error");
});
// res.json({ MyWords: "I am coming from json res" });
});
it must return data from local mongodb database. But it is facing with the problem. Please give me a solution!
both .sendStatus and .json will try to response to client. So the second call will result in this error.
Just use res.json(mybook) and res.send("there were an error") is enough.
In case you want to maintain status code and also send data. Use res.status(500).send("there were an error").
I am new to React Native. I created a Registration App connected to a local PostgreSql Database. I am using Formik for the form, after submitting the form it is recorded in the database. The app refreshes everytime I save the code. However after some refreshes, the data is duplicated in the database. I am using axios and a Rest API. Also using nodemon for the server.
Duplicated Data in the Database
POST REQUEST
const url = 'http://192.168.254.106:5000/users';
handleMessage(null);
handleMessage('Successfully Signed Up!', 'SUCCESS');
try {
const response = await axios.post(url, credentials);
} catch (error) {
handleMessage('An Error Occured.');
}
setSubmitting(false);
}, []);
REST API
const app = express();
const cors = require('cors');
const pool = require('./database');
//middleware
app.use(cors());
app.use(express.json());
//ROUTES
//create user
app.post('/users', async (req, res) => {
try {
const { fullname, email, birthdate, password } = req.body;
const user = await pool.query(
'INSERT INTO users(fullname, email, birthdate, password) VALUES($1, $2, $3, $4) RETURNING *',
[fullname, email, birthdate, password],
);
} catch (err) {
console.error(err.message);
}
});
//get all users
app.get('/users', async (req, res) => {
try {
const allUsers = await pool.query('SELECT * FROM users');
res.json(allUsers.rows);
} catch (err) {
console.error(err.message);
}
});
//get a user
app.get('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const user = await pool.query('SELECT * FROM users WHERE user_id=$1', [id]);
res.json(user.rows);
} catch (err) {
console.error(err.message);
}
});
//update a user
app.put('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const { email } = req.body;
const updateUser = await pool.query('UPDATE users SET email = $1 WHERE user_id=$2', [email, id]);
res.json('Updated!');
} catch (err) {
console.error(err.message);
}
});
//delete a user
app.delete('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const deleteUser = await pool.query('DELETE FROM users WHERE user_id=$1', [id]);
res.json('Deleted!');
} catch (err) {
console.error(err.message);
}
});
app.listen(5000, () => {
console.log('Server is up');
});
I keep getting this MongoDB error, this is my connection to mongodb. I am trying to make a register and login application
const { MongoClient } = require('mongodb');
const uri = "mongodbconnection";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(error => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
this is the signup application
router.post('/register', async (req, res) => {
//hashing the password
const hashedPwd = await bcrypt.hash(req.body.password, saltRounds);
//using passport-local for authentication
const newUser = new User({
email: req.body.email,
password: hashedPwd
})
try {
await newUser.save()
console.log("new user created")
} catch (error) {
if (error) {
console.log(error)
}
}
})
I wrote a little of code to start learning MongoDB with Node.js in JavaScript but it doesn't work but it doesn't
give a error while running probably someone can help me with that.
The Main code:
const mongoose = require('mongoose');
const express = require('express');
const test = express();
const Blog = require('./bdSchema');
//connec to mongodb
const dbURI = 'mongodb+srv://Carsten:<int the real code the password is here>#cluster0.w6iwv.mongodb.net/tomhatesgeschaft?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log("connected to db"))
.catch((err) => console.log(err))
test.get('/add-tomhatesgeschaft', (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
tomhatesgeschaft.save()
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log(err);
});
})
The BDSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BDSchema = new Schema({
title: {
type: String,
required: true,
},
});
const Blog = mongoose.model('Blog', BDSchema);
module.exports = Blog;
In your Node.js code, change the save function as below.
tomhatesgeschaft.save((err,result) => {
if (err){
console.error(err);
}
else{
res.send(result)
})
})
OR
test.get('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
PS: You should not use GET requests for operations such as saving data to the database. Ideally, you should use a POST request.
Example with async:
test.post('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
Today I am facing a silly problem after deploying to Heroku. I have a React front-end. And express back-end. It is a social media app. So in this app, I have a profile page for users. In this page I am using a back-end route to fetch the data of the user. So everything remains good. But once I refresh the page, it starts showing the JSON object coming from the back-end
Before refresh.
after refresh
I am getting this problem after deployment only. I am sharing all of my code which I have written to deploy it to heroku
Server - package.json
{
"name": "server",
"version": "1.0.0",
"description": "Back-end of the dev-media front-end",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"keywords": [
"devr",
"dev-media"
],
"author": "Ratul-oss",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.11.15",
"validator": "^13.5.2"
}
}
server - App.js
require("dotenv").config();
const express = require("express");
const routes = require("./routes/routes");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 8000;
app.use(routes);
app.use(cors());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
app.listen(port, () => console.log(`Listening to http://localhost:${port}`));
And you may also checkout the routes.js where all of my back-end routes/codes are written
const cookieParser = require("cookie-parser");
const express = require("express");
const UserData = require("../models/user");
const routes = express.Router();
require("../dbConnection");
const auth = require("../middlewares/auth");
const cors = require("cors");
const Posts = require("../models/posts");
const bcrypt = require("bcrypt");
const Comments = require("../models/comment");
routes.use(express.json());
routes.use(express.urlencoded({ extended: false }));
routes.use(cookieParser());
routes.use(cors());
// * all the get routes starts from here
routes.get("/auth", auth, (req, res) => {
res.status(200).send(req.user);
});
// for getting the data of a single user by the id
routes.get("/user/:id", async (req, res) => {
try {
const id = req.params.id;
const user = await UserData.findOne({ _id: id });
res.status(201).send(user);
} catch (err) {
res.status(404).json({ err: "User not found" });
}
});
// for getting the data of all users
routes.get("/users", async (req, res) => {
try {
const users = await UserData.find();
res.status(200).send(users);
} catch (err) {
res.status(400).json({ err: "Something is wrong" });
}
});
// for logging out the user
routes.get("/logout", auth, async (req, res) => {
try {
req.user.tokens = req.user.tokens.filter(
(token) => token.token !== req.token
);
res.clearCookie("jwt");
await req.user.save();
res.status(200).send("Succefuly logged out");
} catch (err) {
console.log(err, "from the routes line 23");
}
});
// for getting all the followers
routes.get("/followers/:id", async (req, res) => {
try {
const id = req.params.id;
const user = await UserData.findOne({ _id: id });
res.send(user);
} catch (err) {
console.log(err);
}
});
// for recieving all the posts
routes.get("/posts", async (req, res) => {
try {
const posts = await Posts.find();
res.send(posts);
} catch (err) {
console.log(err);
}
});
// to verify the user posts
routes.get("/post/:id", async (req, res) => {
try {
const id = req.params.id;
const posts = await Posts.find({ userId: id });
res.send(posts);
} catch (err) {
console.log(err);
}
});
// for getting the single post according to the post id
routes.get("/posts/:id", async (req, res) => {
try {
const id = req.params.id;
const post = await Posts.findOne({ _id: id });
res.status(200).send(post);
} catch (err) {
res.status(404).json({ err: "Post Not Found" });
}
});
// for getting the specific comments of a post
routes.get("/comments/:id", async (req, res) => {
try {
const id = req.params.id;
const comments = await Comments.find({ postId: id });
res.send(comments);
} catch (err) {
console.log(err);
}
});
// * all the delete routes starts from here
// for deleting the use account
routes.delete("/deleteAccount/:id", async (req, res) => {
try {
const id = req.params.id;
await UserData.findByIdAndRemove(id).exec();
res.clearCookie("jwt");
res.send("Account Deleted");
} catch (err) {
console.log(err);
}
});
// for deleting the post
routes.delete("/deletepost", async (req, res) => {
try {
const id = req.body.id;
await Posts.findByIdAndRemove(id).exec();
res.send("Post deleted");
} catch (err) {
console.log(err);
}
});
// for deleting a comment
routes.delete("/deleteComment/:id", async (req, res) => {
try {
const id = req.params.id;
await Comments.findByIdAndRemove(id).exec();
res.status(200).send("Deleted");
} catch (err) {
console.log(err);
}
});
// * all the post routes starts from here
// for registering the user
routes.post("/register", async (req, res) => {
try {
const {
name,
email,
bio,
password,
conPass,
country,
gender,
profession,
} = req.body;
if (
(!name, !email, !password, !conPass, !country, !gender, !profession, !bio)
) {
res.status(422).json({ err: "Please fill all the fields properly" });
}
const user = new UserData({
name,
email,
bio,
password,
conPass,
country,
gender,
profession,
});
const emailExists = await UserData.findOne({ email: email });
if (emailExists) {
res.status(401).json({ err: "Email already exists" });
}
if (password !== conPass) {
res.status(403).json({ err: "Password doesn't matched" });
} else if (password === conPass && !emailExists) {
const token = await user.generateToken();
res.cookie("jwt", token);
await user.save();
}
res.status(200).json({ success: "Your account has been registered" });
} catch (err) {
res.status(400).send("Something went wrong");
}
});
// the login route
routes.post("/loginuser", async (req, res) => {
try {
const { email, password } = req.body;
const user = await UserData.findOne({ email: email });
const isMatched = await bcrypt.compare(password, user.password);
if (isMatched) {
const token = await user.generateToken();
res.cookie("jwt", token);
res.status(200).json({ success: "Loggin Successful" });
} else if (!isMatched) {
res.status(403).json({ err: "Your login details are invalid" });
}
} catch (err) {
res.status(400).json({ err: "Invalid Credentials" });
}
});
// for posting any post
routes.post("/postsomething", async (req, res) => {
try {
const name = req.body.name;
const text = req.body.text;
const userId = req.body.userId;
const time = req.body.time;
const date = req.body.date;
if (!text) {
res.status(400).json({ err: "Please type something!" });
}
const post = new Posts({
name: name,
date: date,
time: time,
body: text,
userId: userId,
like: 0,
});
await post.save();
res.status(200).json({ success: "Your Post has been created" });
} catch (err) {
res.status(500).send(err);
}
});
// for posting a comment
routes.post("/postComment", async (req, res) => {
try {
const postId = req.body.postId;
const user = req.body.user;
const commentText = req.body.comment;
const userName = req.body.userName;
const comment = new Comments({
userName,
commentText,
user,
postId,
time: new Date().toLocaleTimeString(),
date: new Date().toLocaleDateString(),
});
await comment.save();
res.status(200).send("Comment Posted");
} catch (err) {
console.log(err);
}
});
// * all the put request starts from here
// for updating the user
routes.put("/updateUser", async (req, res) => {
try {
const { name, email, bio, profession, userId } = req.body;
await UserData.findById(userId, (err, updatedUser) => {
if (name) {
updatedUser.name = name;
}
if (email) {
updatedUser.email = email;
}
if (bio) {
updatedUser.bio = bio;
}
if (profession) {
updatedUser.profession = profession;
}
updatedUser.save();
res.status(200).send("Informations has been updated");
});
} catch (err) {
res
.status(400)
.send(
"Please fill all the fields. If you don't want to update on of them, please type the previous one"
);
}
});
// for following any user
routes.put("/followUser", async (req, res) => {
try {
const followerUser = req.body.authenticateduser; // follower
const followingUser = req.body.user; // this guy will get the follow
await UserData.findById(followingUser._id, (err, user) => {
// when any user will click on the follow button in the front-end, his / her data will be
// stored in the followers field as an object
user.followers = user.followers.concat({ follower: followerUser });
user.save();
res.send("Followed");
});
} catch (err) {
console.log(err);
}
});
// to unfollow an user
routes.put("/unfollowUser", async (req, res) => {
try {
const followerUser = req.body.authenticateduser; // unfollower
const followingUser = req.body.user; // this guy will get the unfollow
await UserData.findById(followingUser._id, (err, user) => {
user.followers = user.followers.filter((follower) => {
return follower.follower._id !== followerUser._id;
});
user.save();
res.send("Unfollowed");
});
} catch (err) {
console.log(err);
}
});
// for liking a post
routes.put("/likePost", async (req, res) => {
try {
const postId = req.body.postId;
const liker = req.body.user;
await Posts.findById(postId, (err, post) => {
post.like = post.like + 1;
post.likers = post.likers.concat({ liker: liker });
post.save();
res.send("Liked");
});
} catch (err) {
console.log(err);
}
});
// for unliking a post
routes.put("/unlikePost", async (req, res) => {
try {
const postId = req.body.postId;
const liker = req.body.user;
await Posts.findById(postId, (err, post) => {
post.like = post.like - 1;
post.likers = post.likers.filter(
(likerUser) => likerUser.liker._id !== liker._id
);
post.save();
res.send("unliked");
});
} catch (err) {
console.log(err);
}
});
module.exports = routes;
You may check out the app I have deployed and figure out the problem https://devr-dev-media.herokuapp.com/. At First open an account then go to your profile page, then try to reload. Your will face the problem.
If you need more information, let me know. Please help me fix that problem with deployment. Thanks for the time :) Have a great day.
The route serving your page in React and the route on your backend are the same that is one of the possible cause. To solve the issues change the name of one maybe add "s" if you wish to maintain the same name. example
instead of
node server.js
`router.get('/name',(req,res)=>{}`
React App.js
<Router>
<Routes>
<Route path="/name" element={<Home/>}/>
</Routes>
</Router>
Try adding "s"
node server.js
`router.get('/names',(req,res)=>{}`
React App.js
<Router>
<Routes>
<Route path="/name" element={<Home/>}/>
</Routes>
</Router>