I am running a React app which has a few methods to update user data. One of these features is to delete movies from a favorites movies list using Axios axios.delete:
removeFavorite(event, favorite) {
event.preventDefault();
console.log(favorite);
axios.delete(`https://flix-app-test.herokuapp.com/users/${localStorage.getItem('user')}/favorites/${favorite}`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
})
.then(response => {
this.getUser(localStorage.getItem('token'));
})
.catch(err => {
console.log(err);
});
}
This is the code living in index.js file:
app.delete('/users/:username/movies/:movieId', passport.authenticate('jwt', { session: false }), function(req, res) {
Users.findOneAndUpdate({ username : req.params.username }, {
$pull : { favorites : req.params.movieId }
},
{ new : true }, // This line makes sure that the updated document is returned
function(err, updatedUser) {
if (err) {
console.error(err);
res.status(502).send("Error: " + err);
} else {
res.json(updatedUser)
}
});
});
For some reason, I am getting a 404 error message when I try to delete a movie:
Error: "Request failed with status code 404" createError
createError.js:16 settle settle.js:17 handleLoad xhr.js:59
dispatchXhrRequest xhr.js:34 xhrAdapter xhr.js:11 dispatchRequest
dispatchRequest.js:59 promise callback*request Axios.js:53 method
Axios.js:68 wrap bind.js:9 getUser main-view.jsx:58 componentDidMount
main-view.jsx:89 React 6 unstable_runWithPriority
scheduler.development.js:818 React 10 parcelRequire<["index.jsx"]<
index.jsx:21 newRequire src.78399e21.js:47 parcelRequire
src.78399e21.js:81 src.78399e21.js:120
I am unable to find out from where the error comes from, once the authorization is fine, the correct movie is picked up as a response and the messages are shown on console accordingly.
Could any of the colleagues here to help me to find where the error lies? Thanks in advance.
PS: #SuleymanSah provided the solution for the 404 error below, BUT I am adding my own solution as well - to the axios.delete action not working. Check below.
The url in your delete does not match the url in the express app.
You should change favorites to movies to resolve the 404 error.
And to be able to delete the favorite, you should update your code using $in.
app.delete('/users/:username/movies/:movieId', passport.authenticate('jwt', { session: false }), function(req, res) {
Users.findOneAndUpdate({ username : req.params.username }, {
$pull : { favorites : { $in: req.params.movieId } }
},
{ new : true },
function(err, updatedUser) {
if (err) {
console.error(err);
res.status(502).send("Error: " + err);
} else {
res.json(updatedUser)
}
});
});
Depending one how you store the favorites, you may need to pull like this:
$pull: {
favorites: {
_id: { $in: req.params.movieId }
}
}
#SuleymanSah has gracefully provided the solution for the 404 error, but for me, the core problem - the axios.delete not removing entries from the list array, remained.
It turned out that axios.delete only could delete entries made by the app using axios.post. Entries created straight on mongoDB array could not be deleted using axios. So, if you are having a hard time deleting entries, try creating a feature to add them first and deleting them after. In my case, only app-created entries could be app-deleted.
Related
I'm using TypeScript for making a GET request to get all members whose isCore is true. I've made several entries in the SQL database but it is showing null in res.json. Is the condition syntax is correct?
code:
router.get('/coreMem', async(req, res)=>{
try {
const core_member_details = await Member.findAll({
where:{
isCore: true
}
})
res.status(200).json(core_member_details);
}
catch (err) {
logger.error(`${err}`);
res.status(500).send('Internal Server/Database Error!');
}
});
I think that it, make sure that the Member model is correctly defined and that it is able to connect to the correct table in the database.
if not, a tip for you which is good debugging method:
To return all the records from the members table, you can use the findAll method without any conditions, like this:
router.get('/coreMem', async(req, res)=>{
try {
const all_member_details = await Member.findAll();
res.status(200).json(all_member_details);
},
catch (err) {
logger.error(${err});
res.status(500).send('Internal Server/Database Error!');
}
});
I'm trying to update a database using Mongoose, but I'm getting this Network error while running my node app.
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/fruitsDB")
const fruitsSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Why no Name?"]
},
rating: {
type: Number,
min: 1,
max: 10
},
review: String
});
const Fruit = mongoose.model("Fruit", fruitsSchema)
Fruit.find(function(err, fruits){
if(err){
console.log(err)
}
else{
mongoose.connection.close();
fruits.forEach(function(fruit){
console.log(fruit.name)
})
}
})
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err){
if(err){
console.log(err)
}
else{
console.log("Successfully updated the document")
}
})
Error: Commnad line error while running the node app
MongoNetworkError: connection establishment was cancelled
at connectionFailureError
at CancellationToken.<anonymous>
at Object.onceWrapper (node:events:641:28)
at CancellationToken.emit (node:events:527:28)
at ConnectionPool.close
at Server.destroy
at destroyServer
at eachAsync
It's a simple Node app created using Mongoose.
Calling the find function last worked for me. I mean, like this -
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err){
if(err){
console.log(err)
}
else{
console.log("Successfully updated the document")
}
})
Fruit.find(function(err, fruits){
if(err){
console.log(err)
}
else{
mongoose.connection.close();
fruits.forEach(function(fruit){
console.log(fruit.name)
})
}
})
Closing the connection should be at end which is the reason why the code is not getting properly executed.
I tried Calling the find function last but still getting the same error like this:
MongoNetworkError: connection establishment was cancelled
I don't know how to tackle this issue when it occurs in a running application but for now if you want to just insert the docs in collection then just comment the .find method completely and then run the application it will be inserted successfully and then comment the .updateOne method and uncomment the .find method by doing you will be successfully added the docs and could get the find result.
I did the same!
OR
I found out that for some reason .find method gets executed before .updateOne so the connection were being closed before the collection gets updated.
So, if we do this it works.
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err) {
if (err) {
console.log(err)
} else {
Fruit.find(function(err, fruits) {
if (err) {
console.log(err)
} else {
mongoose.connection.close();
fruits.forEach(function(fruit) {
console.log(fruit.name)
})
}
});
console.log("Successfully updated the document")
}
})
You can't close the connection in the find method. You are not able to interact with the db after you closed the connection. Just put mongoose.connection.close() at the end.
Just Do something like this:
`People.insertMany([man1, man2, man3],
function (err) {
if (err) {
console.log(err);
} else {
console.log("Successfully saved all
models in the database");
mongoose.connection.close();
}
});`
Closing the connection inside insertmany worked for me
After reading some solutions the TL:DR is: the mongoose.disconnect();, it's the one causing problems, the connection is being terminated before you can update anything
You should be careful while using crud methods on database. Because those methods are asynchronous.
In your case the find method executed first and closed the database connection prior to updateOne method.
Solution: You can solve that by simply changing the logic in your code like embedding find method inside updateOne method or viseversa according to your need.(By embedding we are making a way to execute them in order)
Fruit.find(function(err, fruits) {
if (err) {
console.log(err)
} else {
fruits.forEach(function(fruit) {
console.log(fruit.name)
})
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err) {
if (err) {
console.log(err)
} else {
mongoose.connection.close();
console.log("Successfully updated the document")
}
})
}
})
I have a route like http://localhost:3000/admin/video/edit/5 and the controller looks like this
albumEdit: async (req, res) => {
const editInfoId = req.params.id;
await Movie.findOne({ where: { id: editInfoId } }).then((movie) => {
if (movie) {
res.render('admin/movies/edit', { title: 'Edit Movie On Page One', movie });
}
});
},
for the testing purpose when I type the wrong id after edit/ then the process is freezing after some time I am getting 500 errors.
how to prevent this if someone tries to break my app with the wrong id in the URL? I want something like if anyone tries to do this application redirect to an error page.
I am new in node js express js I need some info.
Your route will freeze if movie is falsy or if fineOne results in an error because for both of these cases you don't send any response.
after some time I am getting 500 errors.
If you run your node server behind a web server then this 500 is due to a timeout because your router does not send a response.
how to prevent this if someone tries to break my app with the wrong id in the URL? I want something like if anyone tries to do this application redirect to an error page.
As with any programming language or code, make sure you handle all control flows and possible exceptions.
Besides that, if you use await you in most of the cases don't want to use .then.
albumEdit: async (req, res) => {
const editInfoId = req.params.id;
try {
let movie = await Movie.findOne({
where: {
id: editInfoId
}
})
if (movie) {
res.render('admin/movies/edit', {
title: 'Edit Movie On Page One',
movie
});
} else {
// either the if is not necessary or you have to also handle the else cases
// send some error response
res.send('error')
}
} catch (err) {
// send some error response
res.send('error')
}
}
For completeness, this is how where you would need to do changes in your code, but as said above don't mix await and then:
albumEdit: async (req, res) => {
const editInfoId = req.params.id;
try {
await Movie.findOne({
where: {
id: editInfoId
}
}).then((movie) => {
if (movie) {
res.render('admin/movies/edit', {
title: 'Edit Movie On Page One',
movie
});
} else {
// either the if is not necessary or you have to also handle the else cases
// send some error response
res.send('error')
}
});
} catch (err) {
// send some error response
res.send('error')
}
}
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)
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);
});
});