MongoDB not getting delete request - node.js

CLIENT:
const handleDelete = (id) => {
console.log(id);
axios.delete(`http://localhost:3001/delete`, {id})
.then(res => console.log(err)})
.catch(err => console.log(err))
}
CONSOLE LOGS THE ID correctly: vv17OZpdGkMwNEv0
SERVER:
cartRoutes.route("/delete").delete((req, res) => {
console.log(req.body);
let db_connect = dbo.getDb("cart");
let myquery = { id: req.body.id };
db_connect.collection("cart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
// console.log("1 document deleted");
});
});
CONSOLE LOGS OUT {}
This is basically copied from MongoDB document, the server(2nd block of code) does not recognize the call from the client. I know that the mongo code works because if I manually put the id in the 'myquery' variable, the item is deleted in the database
Why is that? MongoDB doc has it set up like below which I've tried and still the req.body returns '{}'

Figured it out, not sure if using params is the correct way/best practice
Client
const handleDelete = (e, id) => {
e.preventDefault();
axios.delete(`http://localhost:3001/delete/${id}`)
.then(res => console.log(res))
.catch(err => console.log(err))
}
Server
cartRoutes.route("/delete/:id").delete((req, res) => {
let db_connect = dbo.getDb("cart");
let myquery = { id: res.req.params.id };
db_connect.collection("cart").deleteOne(myquery, function (err, obj) {
if (err) throw err;
// console.log("1 document deleted");
});
});

Related

Get single document in express doesn't jumps to catch

I have the following express code. If I try to get a document with a non-existent id, I get nothing. The problem is that I get 200 as response status and I don't get the Failed message. The code jumps every time into "then".
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
res.send(result);
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}
your finding query response is null so this is not an error. if you send res.status(404).send({"Failed": "Document not found"}); response for not found use this.
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
if(result){
res.send(result);
}else{
res.status(404).send({"Failed": "Document not found"});
}
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}

How do I get the ID of the document I just inserted into MongoDB? (API)

I am trying to get the ID of the document that I just inserted into mongoDB. Here is the node.js code:
app.post("/groups/new", (req, res) => {
const dbGroup = req.body;
Groups.create(dbGroup, (err) => {
if (err) {
res.status(500).send(err);
} else {
var id = dbGroup._id;
res.status(201).send(id);
}
});
});
I have tried various things, like adding a group to the function:
app.post("/groups/new", (req, res) => {
const dbGroup = req.body;
Groups.create(dbGroup, (err, group) => {
if (err) {
res.status(500).send(err);
} else {
var id = group._id;
res.status(201).send(id);
}
});
});
But that also does not work, so I tested if my even get the API response on the front end with:
res.status(201).send("test");
Which works perfectly fine. So I don't know why this doesn't work, because all the documentation says this is the way.
I figured a way to get the id. It may be not the most efficient way, because it sends all the data it gets but it gets the job done.
Backend:
app.post("/groups/new", (req, res) => {
const dbGroup = req.body;
Groups.create(dbGroup, (err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
});
});
Front end:
axios.post("/groups/new", {
groupname: roomName,
}).then((res) => {
roomid = res.data._id;
});

error 'user.findOneAndUpdate is not a function' but data updated

i'm trying to use findOneAndUpdate for change password on mongoose, it's work, database updated
but error message show
"error": "user.findOneAndUpdate is not a function"
this my routes
router.post('/changepass', async (req, res) => {
const { phone, password } = req.body;
try {
const user = await User.findOneAndUpdate({phone},{password})
await user.findOneAndUpdate();
res.send({ user });
} catch (err) {
console.log(err)
res.status(422).send({ error: err.message });
}
});
and this my userSchema
userSchema.pre('findOneAndUpdate', function(next) {
const update = this.getUpdate()
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(update.password, salt, (err, hash) => {
this.getUpdate().password = hash;
return next();
})
})
});
please help me, i'm stuck for hours on this
try removing this line await user.findOneAndUpdate(); This line is causing the error and as per official docs it should be not there
router.post('/changepass', async (req, res) => {
const { phone, password } = req.body;
try {
const user = await User.findOneAndUpdate({phone},{password})
res.send({ user });
} catch (err) {
console.log(err)
res.status(422).send({ error: err.message });
}
});
here is doc reference - https://mongoosejs.com/docs/tutorials/findoneandupdate.html

Subscribe method does not work in angular

product-operations.component.ts
deleteProduct() {
this.productsService.delete_product(this.deleteID).subscribe((res: any) => {
console.log("helloooooo");
});
};
product.service.ts
delete_product(id) {
return this.http.delete("http://localhost:3000/delete_product/" + id);
}
backend
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
console.log("deleted");
})
.catch(err => {
console.log(err);
});
};
Problem:
In the above codes, the deleteProduct function in product-operations.component.ts doesn't work properly. More precisely, it does the removal. But after doing the uninstall, subscribe doesn't run its contents. This prevents my instant update after deletion. How can I solve this?
Try to send a response back from the server.
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
res.send({}) // or res.send({id: id})
console.log("deleted");
})
.catch(err => {
res.status(500)
res.send({error: err})
console.log(err);
});
};

Accessing a passed Object with Express and Axios

In the client side I have :
handleChangeSave(values, id) {
axios.post('/api/users/change' + id, JSON.stringify(values))
.then(resp => {
console.log(resp.data);
})
.catch(function (error) {
console.log(error);
});
}
On the server side I am trying to query for the object and it is coming back empty when it is really not.
router.post('/users/change:id', (req, res) => {
User.findById({ '_id': req.params.id }, (err, user) => {
if(err) return res.status(500).send(err);
let Values = req.query;
console.log(Values); // returns {}
})
});

Resources