Delete object by Id using mongoose - javascript

I'm trying to create API to delete document on mongodb using mongoose.
Here's my route
router
.route("/tasks")
.delete('/:id', function (res, err) {
taskSchema.findByIdAndRemove(req.params.id, (err, tasks) => {
if (err) return res.status(500).send(err);
const response = {
message: "Todo successfully deleted",
id: req.params.id
};
return res.status(200).send(response);
});
});
I get this error
Error: Route.delete() requires a callback function but got a [object String]

/tasks and /tasks/:id are two different routes and you should handle them as such, if you use /tasks to display all tasks, make a route for that, and make a second route for every interaction that you already have an ID for; aka deleting, updating, and use the route without the ID for interactions you don't have an ID for, like creating tasks:
router
.route("/tasks")
.get(/* return all tasks */)
.post(/* create a task */);
router
.route("/tasks/:id")
.delete(function (req, res) {
taskSchema.findByIdAndRemove(req.params.id, (err, tasks) => {
if (err) return res.status(500).send(err);
const response = {
message: "Todo successfully deleted",
id: req.params.id
};
return res.status(200).send(response);
});
});

Related

Vue this.$http.delete() returns 500 internal server only

I'm using axios to connect mysql db with vue frontend, and it's almost done. But the problem is that this.$http.delete() somehow doesn't work at all. I've looked it up but those solutions didn't work. (wrap it {data: book_no}, or {params: book_no}). But it seems like I need to wrap it anyway as an object from vue component when I request(for delete only) the data(req.body.book_no gets undefined data. that's why I added), so I tried few different formats, but it only returns 500 internal server error. Which makes even more 'what?????????' because almost same format of other functions(CRU) are working perfectly.
Please help me out this this.$http.delete method!
Frontend vue component:
btnDelete(book) {
// console.log(book_no);
let book_no = book.book_no;
if (confirm(book_no + " 를 삭제하시겠습니까?")) {
this.$http
.delete("/api/books/delbook", {
book: {
book_no
}
})
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
} else {
return;
}
Backend Books.js delete part
router.delete('/delbook', function (req, res) {
console.log(123)
let bookNo = req.body.book.book_no
console.log(bookNo)
let bookObj = {
'book_no': bookNo
}
console.log(bookObj)
let sql = `DELETE FROM books WHERE book_no = ${bookNo}`
console.log(6666)
db.query(sql, bookObj, function (err, result) {
if (err) throw err;
console.log(err)
console.log(result)
console.log(3234234)
res.send(result)
})
})
error(the only error I've got):
DELETE http://localhost:8080/api/books/delbook 500 (Internal Server Error)

Node req.body undefined on xhttp delete request

I have a fairly extensive Node.js back-end with Express and pg-promise. Most of it is working perfectly as I expected it to.
Currently I am trying to create a function that deletes from multiple tables if I pass in a value for it to do so. My problem is that when I try to use req.body.cont (cont is a variable to continue) I get undefine
I have tried changing the names of the variables, trying to mimic how I sent data to the server before.
function removeUser(req, res, next) {
console.log(req.body.cont);
if (req.body.cont) {
console.log('hello');
deleteLocCustId(req, res, next, req.params.id);
}
db.result('delete from customer where id = $1', req.params.id)
.then(function(result) {
if (!req.body.cont) {
res.status(200).json({
status: 'success',
message: `Removed ${result.rowCount} customer`
});
}
})
.catch(function(err) {
console.log(err);
return next(err);
});
}
When I use this same method to create a customer it works perfectly.
function createCustomer(req, res, next) {
const newCustomer = new PQ(
'insert into customer(customer_name, ID, parent, symID) values ($1, $2, $3, $4)'
);
newCustomer.values = [
req.body.customerName,
req.body.cId,
req.body.parentName,
req.body.symPID
];
db.none(newCustomer)
.then(() => {
if (req.body.locationObject) {
return createLocation(req, res, next);
}
return null;
})
.catch(function(err) {
return next(err);
});
}
When I try to console.log(req.body.cont); I get undefined from my server.

ExpressJS variable undefined

I have an ExpressJS app that when a user makes a POST request to a route, it should lookup the ID in the MongoDB using req.params.formId
I have some console.log statements tfor debugging and so I can see what info is being returned.
The route should lookup the ID passed and when it finds it, use the req.body data and also a field from the MongoDB document but this just seems to return as undefined
Here is the code for the route:
app.post("/api/v1/forms/:formId", (req, res) => {
const { name, email, message } = req.body;
console.log(req.body);
Form.findById(req.params.formId, Form.recipient, err => {
if (err) {
res.send(err);
} else {
const formRecipient = Form.recipient;
const newForm = {
name,
email,
message,
recipient: formRecipient
};
console.log(newForm);
const mailer = new Mailer(newForm, contactFormTemplate(newForm));
try {
mailer.send();
res.send(req.body);
} catch (err) {
res.send(err);
}
}
});
});
So an example, if I make a POST request to localhost:5000/api/v1/forms/5ad90544883a6e34ec738c19 the console.log of newForm shows { name: ' Mr Tester',
email: 'person#example.com',
message: 'Hi there',
recipient: undefined }
The forms Mongoose schema has a field named recipient
the correct way is to provide the fields you want to get as the second argument:
Form.findById(req.params.formId, 'recipient', (err, form) => {
if (err) {
// error handling code
} else {
const formRecipient = form.recipient;
}
...
});
here's the Docs

Having issues editing an existing DB entry with Sails and Waterline

I'm using SailsJS as an API with Waterline connected to a MongoDB. I'm trying to put together an endpoint to edit existing DB entries but can't seem to get it to work and I'm hitting a wall as to why.
My route:
'post /edit/safety/:id': {
controller: 'SafetyController',
action: 'editSafety'
},
My controller function:
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOneById(id).then((err, safety) => {
if (err) {
res.send(500, err);
return;
}
if (!safety) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
safety.save((err, updatedSafety) => {
if (err) {
re.send(500, err);
return;
}
res.send(200, updatedSafety);
});
});
},
Any push in the right direction would be greatly appreciated.
I don't recognize the Safety.findOneById method - is this something you have custom built? If not, then it is likely your problem.
Try swapping it for either:
Safety.findOne(id)
or
Safety.findOne({id: id})
Note that the returned object will be a model instance if the record exists, and undefined otherwise. If you decide to go with Safety.find instead then the returned value will be an array containing all models matching the query.
Looks like the main issue was transposing the response and err objects. It was successfully completing the query, but loading it into the err object which gets caught and a 500 error is thrown. So I changed that and simplified in a few other places.
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOne(id).then((response, err) => {
var safety = response;
if (err) {
res.send(500, err);
return;
}
if (!response) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
Safety.update({
id: id
}, safety)
.then((result) => {
res.json(200, 'Ok!');
})
.catch((err) => {
sails.log.error('SafetyController.editSafety', err);
})
});
},

Mongoose method findbyIdAndRemove is failing when called client-side

I have a route in my app that calls the mongoose method findByIdAndRemove. When I test this route in postman, I can successfully delete documents in my database, but when I call this method from my javascript file in the client, I get an error.
I getting a 404 (the response status I dictated if no document can be found). I also get an error in the terminal saying "can't set headers after they are sent." I'm not sure why I'm getting this error. Why is my route working in postman, but not when I call it from the client-side?
How should I get this working?
Here is my route on the server-side:
exports.deleteEmployee = function (req, res, next) {
const id = mongoose.Types.ObjectId(req.body.id);
Employee.findByIdAndRemove(id, (err, employee) => {
if (err) { return next(err); }
// if no employee with the given ID is found throw 400
if (!employee) { res.status(404).json('No employee with that ID'); }
res.status(200).json(employee);
});
};
Here is where I call this route from the client-side:
export const employeeDelete = ({ id }) => {
const props = { id };
return () => {
axios.delete(`${api.API_ROUTE}/employee/delete`, props)
.then(() => {
// push user back to EmployeeList and reset view stack
Actions.employeeList({ type: 'reset' });
})
.catch(err => {
console.log(err);
});
};
};
You're getting "can't set headers after they are sent." error because you're trying to respond with 200 code after having responded with 400 code.
You should surround the response statements with a if/else statement:
if (!employee) { res.status(404).json('No employee with that ID'); }
else{res.status(200).json(employee);}
It turns out the axios delete method does not take a data object, so when I passed the object called props, it never reached the server. I instead passed id as a url parameter like this:
export const employeeDelete = ({ id }) => {
return () => {
axios.delete(`${api.API_ROUTE}/employee/delete/${id}`)
.then(() => {
// push user back to EmployeeList and reset view stack
Actions.employeeList({ type: 'reset' });
})
.catch(err => {
console.log(err);
});
};
};

Categories