I'm following a tutorial and I get This error:
Cannot read properties of undefined (reading 'env') node: internal/errors:496 ErrorCaptureStackTrace(err); I have searched Google but cannot find a solution i have seen in one searrch hat it could be a typo, I revisited all my code and can't seem to find any typo.
here is my controller code:
//create post
export const createPost = async (req, res) => {
try {
const { title, content } = req.body;
const author = await User.findById(req.user.id);
if (!title || !content) {
throw errorHandler(404, "No title or content found!");
}
if (!author) {
throw errorHandler(404, "No author found!");
}
const newPost = new Post({
title,
content,
cover: req.file ? req.file.filename : null,
author: author._id,
});
await newPost.save();
res.status(202).json(newPost);
} catch (error) {
console.error(error.message);
res.status(error.statusCode).json(error.message);
}
};
//get all posts
export const getAllPost = async (req, res) => {
try {
const posts = await Post.find()
.populate("author", "username")
.sort({ title: 1 });
res.status(200).json(posts);
} catch (error) {
console.error(error.message);
res.status(500).json("Internal server error: 500!");
}
};
//get single post
export const getSinglePost = async (req, res) => {
try {
const { id } = req.params;
const postid = await Post.findById(id).populate("author", "username");
if (!postid) {
throw errorHandler(404, "Post not found!");
}
res.status(200).json(postid);
} catch (error) {
console.error(error.message);
res.status(error.statusCode).json(error.message);
}
};
//update post
export const updatePost = async (req, res) => {
try {
const { id } = req.params;
const { title, content } = req.body;
const author = await User.findById(req.user.id);
const post = await Post.findById(id);
if (!post) {
throw errorHandler(404, "Post not found!");
}
const updateObject = {
title: title,
content: content,
cover: req.file ? req.file.filename : Post.cover,
};
const updatedPost = await Post.findByIdAndUpdate(id, updateObject, {
new: true,
runValidators: true,
});
if (!updatedPost) {
throw errorHandler(404, "Post not found!");
}
res.status(200).json(updatePost);
} catch (error) {
console.error(error.message);
res.status(error.statusCode).json(error.message);
}
};