Hello their I am trying to populate postedBy field on creating a new comment.
When i create a comment i save it on mongodb and also I save comment._id on my feature model (as objectId)
then i am sending res.json(comment)
Can i populate before sending json response?
I also tried but nothing happened
My code-
exports.createComment = async (req, res) => {
console.log("run?");
const { featureId } = req.params;
const { content } = req.body;
const postedBy = req.auth._id;
if (!content) {
return res
.status(400)
.send({ error: "Please provide a content with your comment." });
}
const comment = new Comment({
content,
postedBy,
});
await comment.save();
await comment.populate("postedBy", "_id username");
Feature.findByIdAndUpdate(
featureId,
{ $push: { comments: comment._id } },
{ new: true }
).exec((err, result) => {
if (err) {
return res.json({
error: errorHandler(err),
});
}
});
return res.json(comment);
};```
exports.createComment = async (req, res) => {
console.log("run?");
const { featureId } = req.params;
const { content } = req.body;
const postedBy = req.auth._id;
if (!content) {
return res
.status(400)
.send({ error: "Please provide a content with your comment." });
}
const comment = new Comment({
content,
postedBy,
});
await comment.save();
// One of the ways that I use.
let populatedData= await Comment.findById(comment._id).populate("postedBy", "_id username");
console.log(populatedData)
Feature.findByIdAndUpdate(
featureId,
{ $push: { comments: comment._id } },
{ new: true }
).exec((err, result) => {
if (err) {
return res.json({
error: errorHandler(err),
});
}
});
return res.json(comment);
};
Related
Everything works fine, but the data I get in res() is one step behind. I rewrote the entire code a hundred times and no longer understand what the problem is
here is part of the code backend on express.js, node.js and mongodb:
export const addToCart = async (req, res) => { try {
const cart = await CartModul.findOne({ user: req.userId });
if (cart) {
const product_id = req.body.product_id;
const item = cart.cartItems.find((c) => c.product_id == product_id);
console.log("item", item);
if (item) {
try {
const cart = await CartModul.findOneAndUpdate(
{ user: req.userId, "cartItems.product_id": product_id },
{
"cartItems.$": {
...req.body,
quantity: item.quantity + req.body.quantity,
totalPrice: item.totalPrice + req.body.price,
},
}
);
if (cart) {
return res.status(200).json({ cart });
}
} catch (error) {
return res.status(400).json({ error });
}
} else {
try {
const cart = await CartModul.findOneAndUpdate(
{ user: req.userId },
{
$push: {
cartItems: req.body,
},
}
);
if (cart) {
return res.status(200).json({ cart });
}
} catch (error) {
return res.status(400).json({ error });
}
}
} else {
try {
const cart = new CartModul({
user: req.userId,
cartItems: req.body,
});
cart.save();
res.json(cart);
} catch (error) {
return res.status(400).json({ error });
}
} } catch (error) {
return res.status(400).json({ error })}};
In the else condition add await. i.e.
let newCart = await cart.save();
res.json(newCart);
Use {new: true) in findOneAndUpdate() and make async in moment with save()
do I need to use session.endSession() and session.abortSession() at the end of my code?
Or session.commitTransaction() or any catch will end the session and abort it automatically?
This is the code :
exports.deleteAccount = async (req, res, next) => {
const { userId } = req.body;
try {
const user = await User.findById(userId);
if (!user) {
return next(
new HttpError("Could not find user for the provided id", 404)
);
}
const userDeletingSession = await mongoose.startSession();
userDeletingSession.startTransaction();
await Comment.deleteMany(
{
$or: [{ creator: user._id }, { post: { $in: user.posts } }],
},
{ session: userDeletingSession }
);
await Post.deleteMany(
{ creator: user._id },
{ session: userDeletingSession }
);
await user.remove({
session: userDeletingSession,
});
await userDeletingSession.commitTransaction();
res.status(200).json({ message: "Your user deleted!" });
} catch (err) {
return next(
new HttpError("Deleting your user failed, please try again."),
500
);
}
};
I have a function to check if a user exists, and a function to create a new user in my User model.
What I want to do is call them in the router to check if a user with the email adress in req.body already exists.
If it does, I want to return a message, and if not, I want to create the user.
When I try to call the route in Postman, I get this error in node console :
node_modules/express/lib/response.js:257
var escape = app.get('json escape')
TypeError: Cannot read properties of undefined (reading 'get')
User model :
const Sequelize = require("sequelize");
const connexion = require("../database");
const User = connexion.define(
"users",
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
email: {
type: Sequelize.STRING(100),
allowNull: false,
},
password: {
type: Sequelize.STRING(100),
allowNull: false,
},
},
{
freezeTableName: true
}
);
function checkUser(userEmail) {
const findUser = User.findOne({ where: { userEmail } }).catch((err) => {
console.log(err);
});
if (findUser) {
return res.json({ message: "Cette adresse email est déjà enregistrée" });
} else {
return false;
}
}
function createUser(userData) {
console.log(userData);
User.create(userData)
.then((user) => {
console.log(user);
})
.catch((err) => {
console.log(err);
});
}
module.exports = { createUser, checkUser };
user controller :
const createUser = require("../models/User");
const bcrypt = require("bcrypt");
const saltRounds = 10;
addUser = async (req, res) => {
try {
const userData = req.body;
console.log(req.body);
bcrypt.hash(userData.password, saltRounds, async function (err, hash) {
userData.password = hash;
const newUser = await createUser(req.body);
res.status(201).json({ newUser });
});
} catch (err) {
console.log(err);
res.status(500).json("Server error");
}
};
module.exports = addUser;
user router :
const express = require("express");
const router = express.Router();
const addUser = require("../controllers/userController");
const { checkUser } = require("../models/User");
router.post("/", async (req, res) => {
const { email } = req.body;
const alreadyExists = await checkUser(email);
if (!alreadyExists) {
addUser(req.body);
}
});
module.exports = router;
EDIT : Finally I'm trying a more simple way. I will do the check part directly into the createUser function.
But now, it creates the user even if the email already exists ^^
async function createUser(userData) {
console.log(userData);
const findUser = await User.findOne({ where: userData.email }).catch(
(err) => {
console.log(err);
}
);
findUser
? console.log(findUser)
: User.create(userData)
.then((user) => {
console.log(user);
})
.catch((err) => {
console.log(err);
});
}
i think the problem is with this part you are trying to use res but it doesn't exist in your checkUser function
if (findUser) {
return res.json({ message: "Cette adresse email est déjà enregistrée" });
} else {
return false;
}
try this instead
if (findUser) {
return true });
} else {
return false;
}
UPDATE to fix the problem of user creation if it already exists
async function createUser(userData) {
console.log(userData);
const findUser = await User.findOne({ where: userData.email }).catch(
(err) => {
console.log(err);
}
);
if(!findUser){
findUser
? console.log(findUser)
: User.create(userData)
.then((user) => {
console.log(user);
})
.catch((err) => {
console.log(err);
});
}
}
Problem solved by doing this (thanks super sub for your help):
async function createUser(userData) {
console.log(userData);
const email = userData.email;
const findUser = await User.findOne({ where: { email } }).catch((err) => {
console.log(err);
});
if (!findUser) {
User.create(userData)
.then((user) => {
console.log(user);
})
.catch((err) => {
console.log(err);
});
}
}
im trying to write a function that updates shopping cart which given products info and give user the updated shopping cart, however when I call this function, database is updating but response is not.
Code
export const addToCart: Hapi.Lifecycle.Method = async (request, h, err) => {
const payload: ProductIdPayload = <ProductIdPayload>request.payload;
const userId: string = <string>request.auth.credentials._id;
try {
const [shoppingCart, product] = await Promise.all([
ShoppingCartModel.findOne({ userId: userId }),
ProductModel.findById(payload.productId),
]);
if (product) {
console.log(product);
if (shoppingCart) {
await shoppingCart.updateOne({
$push: { productIds: payload.productId },
$inc: { totalValue: product.price },
});
//above line updates database but below command returns non-updated shopping cart
return h.response({
shoppingCart: shoppingCart,
});
} else {
const newShoppingCart = new ShoppingCartModel({
userId: userId,
productIds: [payload.productId],
totalValue: product.price,
});
console.log(newShoppingCart)
await newShoppingCart.save();
return h.response({ shoppingCart: newShoppingCart });
}
} else {
const error = Boom.notFound("Product Not Found");
return error;
}
} catch (error) {
throw new Error();
}
};
Any idea why is this happening?
Try using:
const updatedShoppingCart = await shoppingCart.updateOne({
$push: { productIds: payload.productId },
$inc: { totalValue: product.price },
});
return h.response({
shoppingCart: updatedShoppingCart,
});
If the above solution doesn't work for you use findOneAndUpdate function on the Model and pass {new: true} in the options.
i am trying to update mongoDB via mongoose using the findOneAndUpdate() method,
i destructure my fields from req.body but if i updated only a single value others are set to null, how do i fix that
CODE
const { name, email, phone, type } = req.body;
await Contact.findOneAndUpdate(
{ _id: req.params.id },
{ $set: { name, email, type, phone } },
{ upsert: true },
(err, updatedContact) => {
if (err) {
console.error(err.message);
res.status(400).send('Could not updat');
} else {
res.json(updatedContact);
}
}
);
});
******************************************
This gives me the desirable result i expected please not that i have not implemented error checking you can do that using the 'express-validator'
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, phone, type } = req.body;
// Build contact object
const updatedContact = {};
if (name) updatedContact.name = name;
if (email) updatedContact.email = email;
if (phone) updatedContact.phone = phone;
if (type) updatedContact.type = type;
try {
await Contact.findOneAndUpdate(
{ _id: req.params.id },
{ $set: updatedContact },
{ new: true }
);
res.json(updatedContact);
} catch (err) {
console.error(err.message);
res.status(400).send('Could not update');
}
});