How to set up an update route in Express - javascript

I am building a MEVN stack CRUD app (Vue, Node, Express, MongoDB). I am attempting to set up the following Express route for my app...
postRoutes.post('/update/:id', async(req, res)=> {
const collection = await loadPostsCollection();
let id = req.params.id;
let result = await collection.findOne(req.params.id)
if (!result) {
res.status(404).send("data is not found");
}
else {
result.title = req.body.title;
result.body = req.body.body;
result.updateOne();
}
});
..in order to update specific data based on the id of that data. After clicking the update button on the front end and triggering an updatePost() method...
updatePost() {
let uri = `http://localhost:4000/posts/update/${this.$route.params.id}`;
this.axios.post(uri, {
title: this.post.title,
body: this.post.body
}).then(() => {
this.$router.push({name: 'posts'});
});
}
...the express route above does not execute. I also tried configuring the route like so...
postRoutes.post('/update/:id', async(req, res)=> {
const collection = await loadPostsCollection();
let id = req.params.id;
let result = await collection.findOne({
_id: new mongodb.ObjectId(id)
});
if (!result) {
res.status(404).send("data is not found");
}
else {
result.title = req.body.title;
result.body = req.body.body;
result.updateOne();
}
});
But this also did not work. Any idea how to set up an update route?
Here are all of my routes:
const express = require('express');
const postRoutes = express.Router();
const mongodb = require('mongodb')
postRoutes.get('/', async (req, res) => {
const collection = await loadPostsCollection();
res.send(await collection.find({}).toArray());
});
postRoutes.post('/add', async (req, res) => {
const collection = await loadPostsCollection();
let task = req.body;
await collection.insertOne(task);
res.status(201).send();
});
postRoutes.get("/edit/:id", async (req, res) => {
const collection = await loadPostsCollection();
let id = req.params.id;
let result = await collection.findOne({
_id: new mongodb.ObjectId(id)
});
if (!result) {
return res.status(400).send("Not found");
}
res.status(200).send(result);
});
postRoutes.post('/update/:id', async(req, res)=> {
const collection = await loadPostsCollection();
let id = req.params.id;
let result = await collection.findOne({
_id: new mongodb.ObjectId(id)
});
// let result = await collection.findOne(req.params.id)
if (!result) {
res.status(404).send("data is not found");
}
else {
result.title = req.body.title;
result.body = req.body.body;
result.updateOne();
}
});
postRoutes.delete('/delete/:id', async (req, res, next) => {
const collection = await loadPostsCollection();
collection.deleteOne({ _id: mongodb.ObjectId(req.params.id) });
res.status(200).send({});
});
async function loadPostsCollection() {
const client = await mongodb.MongoClient.connect(
'mongodb+srv://jsfanatik:1qaz2wsx#cluster0-lv686.mongodb.net/test?retryWrites=true&w=majority',
{
useNewUrlParser: true
}
);
return client.db("test").collection("todos")
}
module.exports = postRoutes;

You request URL is /posts/update/:id but I don't see that path in any express router.
You are missin /posts in your router
postRoutes.post('/update/:id', async(req, res)=> {
const collection = await loadPostsCollection();
let id = req.params.id;
let result = await collection.findOne(req.params.id)
if (!result) {
res.status(404).send("data is not found");
}
else {
result.title = req.body.title;
result.body = req.body.body;
result.updateOne();
}
});

Related

API POST request getting Error: Cannot read properties of undefined (reading 'job_title')

I have built and API with Express to POST a new job in a project I am currently working on. The GET requests work fine, also the DEL, but the POST one is not working. I am connected to a POSTGRES database.
I have defined the following path for the API:
app.use('/api/jobs', jobRoutes);
so when I send a POST request like below:
localhost:4000/api/jobs/createjob
it should work. What is also weird, is that the code was working perfectly before, but now I can't seem to figure it out anymore. I tried looking elsewhere, but I couldn't find any solution when getting this kind of error with APIs.
My API looks like the following:
router.post("/createjob", async (req, res) => {
try {
const {job} = req.body;
const newJob = await pool.query("INSERT INTO job(job_title, job_department, country_id, description, expiration_date) VALUES($1, $2, $3, $4, $5) RETURNING *", [job.job_title, job.job_department, job.country_id, job.description, job.expiration_date]);
res.json(newJob.rows);
} catch (error) {
console.error(error.message);
}
})
I am making the POST request with Postman, and the body looks like this:
{
"description": "job_description",
"job_title": "Back End Developer"
}
When I send the requests, in the terminal shows this error:
Cannot read properties of undefined (reading 'job_title')
Full code of the Routes:
const express = require("express");
const router = express.Router();
const pool = require("../db");
// routes
// get all jobs
router.get('/alljobs', async (req, res) => {
try {
const allJobs = await pool.query("SELECT * FROM job");
res.json(allJobs.rows)
} catch (error) {
console.error(error.message);
}
})
// GET a single job
router.get('/job/:id', async (req, res) => {
try {
const {id} = req.params;
const job = await pool.query("SELECT * FROM job WHERE job_id = $1 ", [id]);
res.json(job.rows)
} catch (error) {
console.error(error.message);
}
})
// create a job
router.post("/createjob", async (req, res) => {
try {
const {job} = req.body;
const newJob = await pool.query("INSERT INTO job(job_title, job_department, country_id, description, expiration_date) VALUES($1, $2, $3, $4, $5) RETURNING *", [job.job_title, job.job_department, job.country_id, job.description, job.expiration_date]);
res.json(newJob.rows);
} catch (error) {
console.error(error.message);
}
})
// update a job
router.patch("/updatejob/:id", async (req, res) => {
try {
const {id} = req.params;
const {description} = req.body;
const updateJob = await pool.query("UPDATE job SET description = $1 WHERE job_id = $2", [description, id]);
res.json(updateJob.rows);
} catch (error) {
console.error(error.message);
}
})
// delete a job
router.delete("/deletejob/:id", async (req, res) => {
try {
const {id} = req.params;
const deleteJob = await pool.query("DELETE FROM job WHERE job_id = $1", [id]);
res.json(deleteJob.rows);
} catch (error) {
console.error(error.message);
}
})
// get all countries
router.get("/countries", async (req, res) => {
try {
const allCountries = await pool.query("SELECT * FROM countries");
res.json(allCountries.rows)
} catch (error) {
console.error(error.message);
}
})
// //create new user
// router.post("/newuser", async (req, res) => {
// try {
// const {user} = req.body;
// const newUser = await pool.query("INSERT INTO users(user_name, email, password, is_candidate, is_recruiter) VALUES($1, $2, $3, $4, $5) RETURNING *", [user.user_name, user.email, user.password, user.candidate, user.recruiter]);
// res.json(newUser.rows);
// } catch (error) {
// console.error(error.message);
// }
// })
module.exports = router;
Full code of my server.js file:
const express = require("express");
const router = require("./routes/jobRoutes");
const jobRoutes = require("./routes/jobRoutes");
const cors = require("cors");
//creates express app
const app = express();
app.use(express.json());
app.use(cors());
//middleware
app.use((req,res,next) => {
console.log("req.path", req.method);
next();
})
app.get("/status", (req, res, next) => {
res.send("connected");
});
// for every other request
app.use('/api/jobs', jobRoutes);
// more middleware
app.use((err, req, res, next) => {
let status = err.status || 500;
let message = err.message;
console.error(err);
return res.status(status).json({
error: { message, status },
});
});
//listen for requests
app.listen(4000, () => {
console.log("listening on port 4000")
});
I tried looking elsewhere, but I couldn't find any solution when getting this kind of error with APIs. The GET and the DEL requests work as expected.

I am connect mongo atlas with this code, but cannot create the database when i send these data

const { MongoClient } = require("mongodb");
const url =
"mongodb+srv://user:password#cluster0.25pjvgx.mongodb.net/products_test?retryWrites=true&w=majority";
const createProduct = async (req, res, next) => {
const newProduct = {
name: req.body.name,
price: req.body.price
};
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db();
const result = db.collection('products').insertOne(newProduct);
} catch (error) {
return res.json({message: 'Could not store data.'});
};
client.close();
res.json(newProduct);
};
const getProducts = async (req, res, next) => {};
exports.createProduct = createProduct;
exports.getProducts = getProducts;
send--
{
"name":"apple",
"price": 99
}
output-
{
"message": "Could not store data."
}
Where is the problem? I try to send the data to the database. But it doesn't work I can not find. please help me.
i used await before db.collection('products').insertOne(newProduct).It works for me

Status Code 502 - Server Error - Node.js Express & MongoDB - Incomplete response received from application

I've noticed that in my application, some pages show a status code 304 whereas some other ones show a status code 200.
Besides that, there is a page that is not displaying on production mode and shows a status code 502.
Why there is such differences in my application for the pages that are working, but showing a status code 304 and 200?
Moreover, why my blog page is not displaying on production mode and shows the status code 502 and displays the following message:
Incomplete response received from application
Though, the blog page is displaying well on development mode and shows the status code 304.
Is there any relation between the status code 304 in development and the status code 502 in production mode?
I mean, the status code 304 in development mode could be the reason for the error and the status code 502 in production mode?
Below is my code.
app.js:
const path = require('path');
const express = require('express');
const session = require('express-session');
const sessionConfig = require('./config/session');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const authRoutes = require('./routes/admin/auth');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const authMiddleware = require('./middlewares/auth-middleware');
const mongoDbSessionStore = sessionConfig.createSessionStore(session);
let port = 3000;
if (process.env.MONGODB_URL) {
port = process.env.MONGODB_URL;
}
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session(sessionConfig.createSessionConfig(mongoDbSessionStore)));
app.use(authMiddleware);
app.use('/', adminRoutes);
app.use('/', authRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
console.error(error);
res.status(500).render('500');
});
db.connectToDatabase()
.then(function () {
app.listen(port);
})
.catch(function (error) {
console.log('La connexion à la base de données a échoué !');
});
routes\home\posts.js:
const express = require('express');
const mongodb = require('mongodb');
const xss = require('xss');
// const uuid = require('uuid');
const db = require('../../data/database');
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/blog', blogControllers.getBlog);
router.get('/blog/:id', blogControllers.getBlogId);
router.get('/blog/:id/comments', blogControllers.getBlogIdComments);
router.post('/blog/:id/comments', blogControllers.postBlogIdComments);
router.get('/profile', blogControllers.getProfile);
module.exports = router;
routes\admin\blog.js:
const express = require('express');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storageConfig });
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/posts', blogControllers.getPosts);
router.get('/new-post', blogControllers.getNewPost);
router.post('/new-post', upload.single('image'), blogControllers.postNewPost);
router.get('/blog/:id/edit', blogControllers.getBlodIdEdit);
router.post('/blog/:id/edit', blogControllers.postBlogIdEdit);
router.post('/blog/:id/delete', blogControllers.postBlogIdDelete);
router.get('/admin', blogControllers.getAdmin);
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
static async fetchAll() {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
return posts;
}
async fetch() {
if (!this.id) {
return;
}
const postDocument = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(this.id) },
{ title: 1, summary: 1, content: 1 }
);
this.title = postDocument.title;
this.summary = postDocument.summary;
this.content = postDocument.content;
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: this.id },
{
$set: {
title: this.title,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
async delete() {
if (!this.id) {
return;
}
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: this.id });
return result;
}
}
module.exports = Post;
controllers\post-controllers.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const Post = require('../models/post');
const ObjectId = mongodb.ObjectId;
async function getBlog(req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({
title: 1,
summary: 1,
content: 1,
'author.name': 1,
imagePath: 1
})
.toArray();
console.log(posts);
res.render('posts', { posts: posts });
}
async function getBlogId(req, res, next) {
let postId = req.params.id;
try {
postId = new ObjectId(postId);
} catch (error) {
return res.status(404).render('404');
// return next(error);
}
const post = await db
.getDb()
.collection('posts')
.findOne({ _id: postId }, { summary: 0 });
if (!post) {
return res.status(404).render('404');
}
post.humanReadableDate = post.date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
post.date = post.date.toISOString();
res.render('post-detail', { post: post, comments: null });
}
async function getBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const comments = await db
.getDb()
.collection('comments')
.find({ postId: postId })
.toArray();
res.json(comments);
}
async function postBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const newComment = {
postId: postId,
title: xss(req.body.title),
text: xss(req.body.text)
};
await db.getDb().collection('comments').insertOne(newComment);
res.json({ message: 'Commentaire ajouté !' });
// res.status(500).json({ message: 'Error!' });
}
function getProfile(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
res.render('profile');
}
async function getPosts(req, res) {
const posts = await Post.fetchAll();
res.render('posts-list', { posts: posts });
}
async function getNewPost(req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
}
async function postNewPost(req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
}
async function getBlodIdEdit(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.fetch();
if (!post.title || !post.summary || !post.content) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
}
async function postBlogIdEdit(req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[, , ,], // pass 3 undefined arguments
req.params.id
);
await post.save();
res.redirect('/posts');
}
async function postBlogIdDelete(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.delete();
res.redirect('/posts');
}
async function getAdmin(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
}
module.exports = {
getBlog: getBlog,
getBlogId: getBlogId,
getBlogIdComments: getBlogIdComments,
postBlogIdComments: postBlogIdComments,
getProfile: getProfile,
getPosts: getPosts,
getNewPost: getNewPost,
postNewPost: postNewPost,
getBlodIdEdit: getBlodIdEdit,
postBlogIdEdit: postBlogIdEdit,
postBlogIdDelete: postBlogIdDelete,
getAdmin: getAdmin
};

NodeJs - TypeError: Cannot read property 'url' of null, but the app is working fine

UPDATE: I it checks for /:slug even if i go to a different route, i think thats causing the problem.
I'm trying to create a URL Shortener with Nodejs, Expressjs, MongoDB and EJS.
Even though my application is working perfectly, I keep getting this error in terminal:
My routes :
const express = require("express");
const URLs = require("../models/urls");
const { findById, find } = require("../models/urls");
const router = express.Router();
router.get("/", (req, res) => {
res.render("index", { shortUrl: new URLs() });
});
router.post("/redirect", (req, res) => {
let url = req.body.url;
let slug = req.body.slug;
let shortenUrl = new URLs({
url: url,
slug: slug,
});
shortenUrl.save();
res.render("shortenUrl", { shortenUrl });
});
router.get("/about", (req, res) => {
res.render("about");
});
router.get("/contact", (req, res) => {
res.render("contact");
});
router.get("/all", async (req, res) => {
try {
var shortUrls = await URLs.find({});
res.render("all", { shortUrls });
} catch (error) {
console.log(error);
}
});
//:TODO
router.get("/:slug", async (req, res) => {
var shortUrl = await URLs.findOne({ slug: req.params.slug }).exec();
try {
console.log(shortUrl);
var urls = await shortUrl.url;
if (urls.includes("http", 0)) {
return res.redirect(urls);
} else {
return res.redirect(`http://${urls}`);
}
} catch (error) {
console.log(error);
}
});
module.exports = router;
I didn't get this error until I made API for the app (in separate routes file).
Also in my server I'm using:
app.use(bodyParser.urlencoded({ extended: false }));
and using:
app.use(express.json());
doesn't help either.
Any help would be appreciated, Thank you c:
I added an if statement to the route and that solved the problem, thanks to #Pukka c:
router.get("/:slug", async (req, res) => {
var shortUrl = await URLs.findOne({ slug: req.params.slug }).exec();
if (shortUrl) {
try {
console.log(shortUrl);
var urls = await shortUrl.url;
if (urls.includes("http", 0)) {
return res.redirect(urls);
} else {
return res.redirect(`http://${urls}`);
}
} catch (error) {
console.log(error);
}
}

How to modify common mongodb query to async with try and catch

This is my code with written with express js
this query works but I think that using async is more reliable than this
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get("/", async (req, res) => {
// this is myquery code with right result
client.connect((err) => {
assert.equal(null, err);
const db = client.db(db_n)
db.collection("list").find({}).toArray((err, result) => {
if(err) throw res.send({ status: "Error when react data", bool: false}).status(450);
res.send(result).status(200);
})
})
});
Try this, not exactly the same as yours, but will give you the idea on how to use async/await with try/catch
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get('/', async (req, res) => {
// Connect client if it's not connected
if(!client.isConnected()) {
await client.connect();
// you can also catch connection error
try {
await client.connect();
catch(err) {
return res.status(500).send();
}
}
const db = client.db(db_n);
try {
// Run queries
const result = db.collection("list").find({});
res.json(await result.toArray());
} catch (err) {
// Catch any error
console.log(err.message);
res.status(450).send();
}
});
I have not tested this, but try something along the lines of:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
let client;
const getDb = async () => {
// If we don't have a client, create one.
if (!client) client = new MongoClient(url, { useUnifiedTopology: true });
// If we are not connected, then connect.
if (!client.connected()) await client.connect();
// Get our database
return client.db(db_n);
}
app.get("/", async (req, res) => {
try {
const db = await getDb();
const results = await db.collection("list").find({}).toArray();
res.send(result).status(200);
} catch (err) {
res.send({ status: "Error when react data", bool: false}).status(450);
}
});

Categories