User.destroy is not a function - node.js

I use the oracle-sage library. And when I want to delete a record, an error occurs.
{
"success": false,
"message": "User.destroy is not a function"
}
How can fix this?
const User = require('../models/User')
const errorHandler = require('../utils/errorHandler')
module.exports.remove = async function (req, res) {
try {
await User.destroy({
USER_ID: req.params.USER_ID
})
res.status(200).json({
message: 'User deleted.'
})
} catch (e) {
errorHandler(res, e)
}
}

Probably .destroy is not a static method, needs an instantiated object. You can try to get the user object first then destroy it.
try {
let user = await User.findOne({ USER_ID: req.params.USER_ID});
user.destroy().then(function(){
res.status(200).json({
message: 'User deleted.'
})
});
} catch (e) {
errorHandler(res, e)
}

Another way to implement destroy method is as below
const deleteUser = async (req,res) => {
console.log('Deleting User by Id')
const userId = await req.params.id
const user = await User.destroy({
where:{
id : userId
},
raw:true
}).catch(error=>console.log(error))

Related

MongoDB saves the necessary data to the collection, but outdated data goes to res()

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()

How to use populate on saving new data on mongoose

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);
};

got `{}` when set a field in mongodb to `undefined` using mongoose

I'm facing a weird problem
I'm using mongoose 5.12.8, I try to delete a user's image with this route
router.delete('/users/me/avatar', auth, async(req, res) => {
try {
req.user.avatarObj = undefined
await req.user.save()
res.send({ message: "Deleted user's avatar" })
} catch (error) {
res.status(500).send(error.message)
}
});
but when I use get route, i got req.user.avatarObj is still an empty object {}
//get user avatar
router.get('/users/:id/avatar', async(req, res) => {
try {
const user = await User.findById(req.params.id);
console.log(user.avatarObj) // print {} ?????????
console.log(user) //user has no avatarObj field
if (user && user.avatarObj) {
res.set('Content-Type', user.avatarObj.contentType);
res.send(user.avatarObj.data);
} else {
throw new Error('Not found user or image');
}
} catch (err) {
res.status(404).send({ error: err.message });
}
});
this is my userSchema
avatarObj: {
data: Buffer,
contentType: String
}
and some middleware
//hash plain text password before saving
userSchema.pre('save', async function(next) {
const user = this
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 10)
}
next()
});
//remove all tasks before remove user
userSchema.pre('remove', async function(next) {
await Task.deleteMany({ owner: this._id })
next()
});
My question is: Why user.avatarObj is still an empty object?
Thank you guys!

how do I update an object in Sequelize

I am new to Sequelize, and I'm trying to update an object, but it's not working. here is my code
const updateEmployee = async (req, res) =>{
let {full_name, email, phone_number, address} = req.body
const id = req.params.id;
Employee.findOne({
where: { id: id }
})
.then(employee => {
employee.update({
full_name: full_name.full_name,
email: email.email,
phone_number: phone_number.phone_number,
address: address.address
})
})
}
please assist !!
You can use the update() method and add the search scope as second argument. The update() method is a Promise that returns an array with with one or two elements. The first element is always the number of affected rows. See the sequelize API documentation for more details on the update() method.
Your code should look something like this. I have not tested this so you might need to tweak the code a bit:
updateUser: async (req, res) => {
try {
await employee.update(req.body, {
where: {
id: req.body.id
}
})
.then((result) => {
// check the first element in the array if there are rows affected
if (result[0] > 0) {
res.status(200).send({ message: 'data found' });
} else {
return res.status(422).send({ message: 'no data found' });
}
})
}
catch(error) {
console.log(error);
return res.status(500).send({ message: 'updating user failed' });
}
}
When you are using async function. It is best to use await also don't use promise based format this in below api first I am finding user with that id from database if its present it ill update user else it will throw error that there is no data with that id
updateUser: async (req, res) => {
try {
let data = await employee.findOne({
where: {
id: req.body.id
}
});
if (data) {
await employee.update(req.body, { where: { id: req.body.id } });
return res.status(200).send({message: data found});
}
else {
return res.status(422).send({message: no data found});
}
} catch (err) {
console.log(err)
return res.status(500).send({message: Internal server error);
};
}

How to send an error message from the apollo- server

this my code
in apollo clients I use useMutation.
apollo clients
const [addTodo, { loading, error, data }] = useMutation(gql);
apollo-server
Mutation: {
signUp: async (_, formSignUp, { models: { User }, res }) => {
try {
const user = new User(formSignUp);
await user.save();
const token = await user.generateAuthToken();
res.cookie("darkAmasia", token, {
httpOnly: true
});
return "string";
} catch (error) {
?????????
}
}
}
What should I write in catch ? to send a message {status:400,error:true}in useMutation error.
I heard that throw new ApolloError is used for these purposes.But I do not know how to do it.
Read more about error handling here
you can create your own Error class which extends ApolloError and pass status as default attribute.
Mutation: {
signUp: async (_, formSignUp, { models: { User }, res }) => {
try {
const user = new User(formSignUp);
await user.save();
const token = await user.generateAuthToken();
res.cookie("darkAmasia", token, {
httpOnly: true
});
return "string";
} catch (error) {
throw new ApolloError("Something went wrong", "BAD_INPUT",{status:400,error:true});
}
}
}

Resources