PostsRouter.post("/ALL", (req, res) => {
const { subreddit, title, user, body } = req.body;
const post = new PostMessage({
postID: uuidv4(),
subreddit: subreddit,
title: title,
user: user,
body: body,
});
console.log(post);
async function _internal() {
try {
const newPost = await post.save();
res.status(201).json(newPost);
} catch (error) {
res.status(400);
}
}
_internal();
});
This function exactly as it is was working earlier but now this method and another PATCH method I defined elsewhere are failing because the promise is never fulfilled on the first line of the try block that saves the new data to the database "const newPost = await post.save()". Would anyone know what could be causing an issue like this? When I make a call to this API there are no error messages from the backend. I also included an image showing how I am making the POST request and the error I am getting.
If you want to create a document in the database and use that document for any further operations then you can use the below code for that purpose.
PostsRouter.post("/ALL", async(req, res) => {
const { subreddit, title, user, body } = req.body;
try {
// PostMessage is the Model
const newPost = await PostMessage.create({
postID: uuidv4(),
subreddit: subreddit,
title: title,
user: user,
body: body,
});
console.log(newPost);
res.status(201).json(newPost);
}catch (error) {
res.status(400);
}
}
});
Hope this helps.
Related
I am very new to the MERN stack and I would like some help figuring out this error. I'm trying to check if an email is already in the database upon creating a new user. Can anyone tell me why I am getting this error?
The model and scheme
//schema
const Schema = mongoose.Schema;
const VerificationSchema = new Schema({
FullName: String,
email: String,
password: String,
date: Date,
isVerified: Boolean,
});
// Model
const User = mongoose.model("Users", VerificationSchema);
module.exports = User;
The Api
const express = require("express");
const router = express.Router();
const User = require("../Models/User");
router.get("/VerifyEmail", (req, res) => {
console.log("Body:", req.body);
const data = req.body;
const newUser = new User();
newUser.find({ email: data.email }, function (err, newUser) {
if (err) console.log(err);
if (newUser) {
console.log("ErrorMessage: This email already exists");
} else {
console.log("This email is valid");
}
});
res.json({
msg: "We received your data!!!",
});
});
module.exports = router;
The api caller using axios
const isEmailValid = (value) => {
const info = {
email: value,
};
axios({
url: "http://localhost:3001/api/VerifyEmail",
method: "get",
data: info,
})
.then(() => {
console.log("Data has been sent");
console.log(info);
})
.catch(() => {
console.log("Internal server error");
});
};
if you have body in your request, change the type of request to POST...
after that for use find don't need to create a instance of model, use find with Model
router.get("/VerifyEmail", (req, res) => {
console.log("Body:", req.body);
const data = req.body;
User.find({ email: data.email }, function (err, newUser) {
if (err) console.log(err);
if (newUser) {
console.log("ErrorMessage: This email already exists");
} else {
console.log("This email is valid");
}
});
res.json({
msg: "We received your data!!!",
});
});
I prefer to use async/await and don't use Uppercase world for routing check the article: like this
router.post("/verify-email", async (req, res) => {
try {
let { email } = req.body;
let newUser = await User.findOne({ email });
if (newUser) {
console.log("ErrorMessage: This email already exists");
} else {
console.log("This email is valid");
}
} catch (error) {
res.json({
msg: "somthing went wrong",
});
}
res.json({
msg: "We received your data!!!",
});
});
The proper way to query a Model is like so:
const User = mongoose.model('Users');
User.find({<query>}, function (err, newUser) {...
So you need to get the model into a variable (in this case User) and then run the find function directly against it, as opposed to running it against an object you instantiate from it. So this is incorrect:
const newUser = new User();
newUser.find(...
So assuming all your files and modules are linked up correctly, this should work:
const User = require("../Models/User");
User.find({<query>}, function (err, newUser) {...
The problem wasn't actually the mongoose function but I needed to parse the object being sent.
let { email } = JSON.parse(req.body);
Before parsing the object looked like {"email" : "something#gmail.com"}
and after parsing the object looked like {email: 'something#gmail.com'}
I also changed the request from 'get' to 'post' and instead of creating a new instance of the model I simply used User.find() instead of newUser.find()
GoodDay Experts,
I've tried following code but it did not work, and it gives me null value.. maybe my routes are wrong but basically it works the way on other routes... and here is my backend for delete case: manage.js/actions
export const removeRecipient = (payload) => async (dispatch) => {
try {
const res = await axios.delete(
`${_config.MAT_URL}/api/1/customer/delete`,
payload
);
dispatch({
type: DELETE_CUSTOMER,
payload: res.data,
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: { err },
});
}
};
and for my routes which is the mongoose query for findOneAndDelete, under customer.js :
router.delete("/delete", (req, res) => {
Customer.findOneAndDelete({ _id: req.params.id }, (err, Customer) => {
if (!err) {
res.json({ msg: "customer deleted", deleted: Customer });
} else {
console.log("Error removing :" + err);
}
});
});
And for the front end im using "AiOutlineDelete" which was coded as :
const handleDelete = (id) => {
console.log('delete')
removeRecipient(id)
}
<a
id={`delete-${rowIndex}`}
className="anchor-action-delete"
href="#foo"
onClick={(e) => {
e.preventDefault();
handleDelete(row);
}}>
thanks have a great day
There are 2 problems in your code:
req.params.id is meant for urls of the form /delete/:id which is obviously not your route, you should change it to req.query.id instead which matches query parameters in the url such as /delete?id=123.
The default type of _id is ObjectId, under the assumption you did not change this you need to cast your req.query.id which is type string to ObjectId.
It looks like you're using mongoose so here's mongoose syntax:
const mongoose = require("mongoose");
router.delete("/delete", (req, res) => {
Customer.findOneAndDelete({ _id: new mongoose.Types.ObjectId(req.query.id) }, (err, Customer) => {
if (!err) {
res.json({ msg: "customer deleted", deleted: Customer });
} else {
console.log("Error removing :" + err);
}
});
});
For nodejs native Mongo package:
import {ObjectId} from "mongodb";
...
new ObjectId(req.query.id)
I dont see you sent the id to the backend but you are trying to retrieve it from req.params.id try passing the id like "delete/:id" at the end of the link and specify this in the routes aswell.
if that doesnt fix try the below code this for routes
if nothing works check this, In the component you need to send the id(object id) but i see "row" what is the value of row? if the row value is not the id in the database then it wont delete. if this your issue try inspecting the code by keeping breakpoints or write a console.log() to check the value of "row" .
try {
const removedProject = await Customer.remove({
_id: req.params.id
})
res.json(removedProject)
} catch (err) {
res.json({
message: err
})
}
I am making a react-native mobile app and I am having trouble passing the users info that created the post to the home page in the post detail. I can pass the userID but for some reason when I add the rest of the info to the payload I can't create a post. Please help.
BACKEND
This is the requireAuth file that requires authentication before performing a tast. My code for the user is here as well at the bottom---
const mongoose = require("mongoose");
const User = mongoose.model("User");
module.exports = (req, res, next) => {
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).send({ error: "You must be logged in." });
}
const token = authorization.replace("Bearer ", "");
jwt.verify(token, "mySecretKey", async (err, payload) => {
if (err) {
return res.status(401).send({ error: "You must be logged in." });
}
const { userId, name, phone, email } = payload;
const user = await User.findById(userId);
req.user = user;
console.log(req.user);
next();
});
};
This is the POST route for the Item---
router.post("/items", requireAuth, async (req, res) => {
const { title, category, detail, condition, price } = req.body;
if (!title || !category || !detail || !condition || !price) {
return res.status(422).send({
error: "You must provide a title, category, detail, condition, and price"
});
}
try {
const item = new Item({
title,
category,
detail,
condition,
price,
userId: req.user._id
});
await item.save();
res.send(item);
} catch (err) {
res.status(422).send({ error: err.message });
}
});
FRONT-END
This is my createItem function in the itemContext file---
const createItem = dispatch => async ({
title,
category,
detail,
condition,
price
}) => {
try {
const response = await sellerApi.post("/items", {
title,
category,
detail,
condition,
price
});
//this is the other place the error might be happening i need this to save in the phone local storage
dispatch({ type: "create_item", payload: response.data });
navigate("Home");
} catch (err) {
console.log(err);
}
};
All I am trying to do it is when the post is being displayed so is the info of the post creator
For existing post in the database: If you are referencing your user in post model like this
const Post = mongoose.model('Post', {
// other fields
userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
}
})
then you can use populate to fetch user of that post.
const post= await Post.findById('5c2e505a3253e18a43e612e6')
await post.populate('userId').execPopulate()
console.log(post.userId)
I have created a Node.js API and am making requests to it using Next.js
Here is my Node.js controller. I am using express validator for validation.
If I fill in the form correctly, it works and the data is saved in mongo as expected. However, I want to send the validation errors back to the client when the form isn't filled in correctly. If I look in console, I can see the errors in the network tab.
exports.register = async (req, res) => {
// check if user exists in the database already
const emailExists = await User.findOne({ email: req.body.email });
if (emailExists) return res.status(400).send("Email already exists");
// hash password
const salt = await bcrypt.genSalt(10);
// hash the password with a salt
const passwordhash = await bcrypt.hash(req.body.password, salt);
// create new user
var user = new User({
name: req.body.name,
email: req.body.email,
password: passwordhash
});
try {
user = await user.save();
res.send({ user: user._id });
} catch {
res.status(400).send(err);
}
};
In Next.js, here is the code for making the http request
handleSubmit = event => {
const { name, email, password } = this.state;
event.preventDefault();
const user = {
name,
email,
password
};
try {
register(user);
} catch (ex) {
console.log(ex);
}
};
export const register = async user => {
const data = await http.post("http://localhost:8000/api/user/register", user);
console.log(data);
return data;
};
In console all I see is the below. So the console.log I am doing in the catch isn't working.
POST http://localhost:8000/api/user/register 422 (Unprocessable Entity)
Uncaught (in promise) Error: Request failed with status code 422
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:59)
That's because the catch statement isn't being run because the function isn't throwing an exception by itself. You should add the error handling inside the function like this:
try {
register(user);
} catch (ex) {
console.log(ex);
}
};
export const register = async user => {
const data = await http.post("http://localhost:8000/api/user/register", user).catch((e) {
throw new Error(e);
});
console.log(data);
return data;
};
I managed to get it working like this:
try {
const response = await register(user);
console.log(response);
} catch (ex) {
if (ex.response && ex.response.status === 422) {
const errors = ex.response.data.errors;
this.setState({ errors });
}
}
I'm trying to post to mongodb using express nodejs and this is the code of add route:
router.post('/add', (req, res) => {
const validating = userValidating(req.body);
if (validating.error) {
res.status(400).send(validating.error.details);
} else {
var path = "images/"+req.file.image;
res.send(path);
var image = req.files.image;
fileName = uuidv1();
const user = new User({
_id: new mongoose.Types.ObjectId(),
image: req.file.image,
title: req.body.title
});
const v = user.validateSync();
if (v)
res.status(400).send('somthing wrong');
user.save()
.then(result => {
res.send('You have added a new user');
image.mv(`./public/images/${fileName}.png`, function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
console.log(result);
})
.catch(err => {
res.status(401).send(err);
console.log(err);
});
}
});
and this is the function of validation that I used above:
function userValidating(user) {
const userSchema = {
'image': Joi.string().required(),
'title': Joi.string().required()
}
return Joi.validate(user, userSchema);
}
when I tried in postman using form-data like this:
you can see that I get this error of image is required even if I change the image to req.body.image instead of req.file.image
also I tried to use Body raw in postman instead of form-data and write json like this:
{
"image": "uuu",
"title": "uuuu"
}
and it works fine
what's the problem with code?