How can I get a full data except deleted, after delete?
Project.findOneAndRemove({_id: projectID, name: projectName},
function(err, project){
if (err) {
return res.json({message: 'Error on the server!', status: 500 });
}
// Here I need a full data except deleted one
console.log(project)
return res.json({project, status:200});
}
)
or Do I find again inside success callback to get full data?
Project.find({}, function(err, projects){
if (err) return res.json({message: 'Error on the server!', status: 500 });
return res.json(projects);
});
This might help you.
router.post('/deleteAndReturn', async (req, res) => {
try {
await Project.findOneAndRemove({ _id: projectId })
const projects = await Project.find({})
return res.status(200).json(projects)
} catch (err) {
res.status(500).send("Server Error")
}
})
Related
i want to delete user and his photo from directory si i have made this method , it delete the user but the photo still in the directory ,
export function deleteUser(req, res, next) {
userModel.findByIdAndRemove(req.params.id, (err, user) => {
if (err) next(err)
else {
const filename = user.photo.split('/images/')[1]
fs.unlink(`images/${filename}`, () => {
res.status(200).json({ message: 'Deleted!' })
})
}
})
}
how can i fix it?
fs.unlink might also throw an error, but you're not handling it currently. You would send the 200 response even if there's an error.
Try this:
fs.unlink(`images/${filename}`, (err) => {
if (err) next(err)
res.status(200).json({ message: 'Deleted!' })
})
i want to delete the images that i uploaded in the server but every time i get an error
and only the element in the mongodb document are being deleted
this is my code
exports.removeImage = async (req, res) => {
try {
fs.unlinkSync('./images/'+req.filename);
const deleteImage = await Image.findByIdAndDelete(req.params.id)
res.json({ message: 'deleted Image successfully' });
}
catch (err) {
console.log(err);
res.status(500).json({ message: 'Internal server error' });
}
}
i think the problem is in req.filename its returning an undifiened value i tried req.body.filename but still no result
i resolved the problem by adding
const image = await Image.findById(req.params.id)
then i used image.filename in fs.unlinkSync
this is the result :
exports.removeImage = async (req, res) => {
try {
const image = await Image.findById(req.params.id)
fs.unlinkSync('./images/'+image.filename);
const deleteImage = await Image.findByIdAndDelete(req.params.id)
res.json({ message: 'deleted Inspecstib successfully' });
}
catch (err) {
console.log(err);
res.status(500).json({ message: 'Internal server error' });
}
}
validateRegister: async (req, res, next) => {
UserModel.findOne({email:req.body.email}, (err, example) => {
console.log(example);
if(err) console.log(err);
if(example) {
res.status(400).json({message: "Email already registered!"});
res.end() //next('route')
}
});
console.log("test");
const user = new UserModel(req.body);
await user.save((err) => {
if (err) return res.status(500).json({ message: "Database issue!" });
});
next();
},
Ok, I tried to insert user data if it is not already in the database using mongoose. If the User regarding the email is already in the database the response should be ended and the user not inserted. I tried to end the response with res.end() and next('route'), but nothing seems to work, the console.log("test") still runs.
Error:
events.js:353
throw er; // Unhandled 'error' event
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)
Thanks for your help
Code below callback function gets executed before callback gets completed and multiple res.send happened.
you can try this
validateRegister: async (req, res, next) => {
UserModel.findOne({ email: req.body.email }, (err, example) => {
console.log(example);
if (err) {
console.log(err);
return res.status(500).json({ message: "Something went wrong" });
}
if (example) {
return res.status(400).json({ message: "Email already registered!" });
}
console.log("test");
const user = new UserModel(req.body);
await user.save((err) => {
if (err) return res.status(500).json({ message: "Database issue!" });
});
});
next();
}
Or
validateRegister: async (req, res, next) => {
try {
let example = await UserModel.findOne({ email: req.body.email });
console.log(example);
if (example)
return res.status(400).json({ message: "Email already registered!" });
console.log("test");
const user = new UserModel(req.body);
await user.save((err) => {
if (err) return res.status(500).json({ message: "Database issue!" });
});
next();
} catch (err) {
console.log(err);
return res.status(500).json({ message: "Something went wrong" });
}
}
you can add return before returning response in the case of user email already found.
What seems to happen is that your program is calling res two times
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);
};
}
I had this route and it worked perfectly
router.get('/api/User/:id',async(req,res)=>{
try {
const{id}=req.params;
let result =await pool1.request()
.input('Iduser', sql.Int, id)
.execute('GetUser')
res.json(result);
}
catch (err) {
res.json({ error: 'Does Not exist' })
}
});
But I want to separate the function and leave the route as clean as possible, try to separate it as follows but I get the following error: TypeError: one is not a function
Route
router.get('/api/User/:id', async(req,res)=>{
try {
res.json((await one(req.params.id))[0]);
} catch (err) {
console.log(err);
res.sendStatus(500);
}
})
Function
const one = async(id)=>{
return new Promise((resolve,reject)=>{
pool.request()
.input('Iduser', sql.Int, id)
.execute('User')((err,results) =>{
if(err){
return reject(err);
}
resolve(results);
});
});
}
What is my mistake, am I calling the function wrong?
to make your code cleaner you can do this :
const getUserById =async(req,res)=>{
try {
const{id}=req.params;
let result =await pool1.request()
.input('Iduser', sql.Int, id)
.execute('GetUser')
res.json(result);
}
catch (err) {
res.json({ error: 'Does Not exist' })
}
}
router.get('/api/User/:id',getUserById);
also to make it cleaner more you can do it like this
export const asyncHandler = (fn) => async (request, response, next) => {
try {
return await fn(request, response, next);
} catch (error) {
return next(error); // or response.json({ error: 'Does Not exist' })
}
};
const getUserById =async(req,res)=>{
const { params: { id } }=req;
const result =await pool1.request()
.input('Iduser', sql.Int, id).execute('GetUser');
return res.json(result);
}
router.get('/api/User/:id',asyncHandler(getUserById));
Thanks mate, I solved why he tells me that it was not a function, I was not calling it well but the way you explain it the route is much cleaner
function
const one = async(id)=>{
return new Promise((resolve,reject)=>{
pool.request()
.input('IdUser', sql.Int, id)
.execute('GetUser',(err,results)=>{
if(err){
return reject(err);
}
resolve(results);
}
)
});
}
route
router.get('api/user/:id', async(req,res)=>{
try {
let result=await m.one(req.params.id);
res.json(result);
} catch (error) {
console.log(error);
res.sendStatus(500);
}
})