GoodDay Experts,
I've tried following code but it did not work, and it gives me null value.. maybe my routes are wrong but basically it works the way on other routes... and here is my backend for delete case: manage.js/actions
export const removeRecipient = (payload) => async (dispatch) => {
try {
const res = await axios.delete(
`${_config.MAT_URL}/api/1/customer/delete`,
payload
);
dispatch({
type: DELETE_CUSTOMER,
payload: res.data,
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: { err },
});
}
};
and for my routes which is the mongoose query for findOneAndDelete, under customer.js :
router.delete("/delete", (req, res) => {
Customer.findOneAndDelete({ _id: req.params.id }, (err, Customer) => {
if (!err) {
res.json({ msg: "customer deleted", deleted: Customer });
} else {
console.log("Error removing :" + err);
}
});
});
And for the front end im using "AiOutlineDelete" which was coded as :
const handleDelete = (id) => {
console.log('delete')
removeRecipient(id)
}
<a
id={`delete-${rowIndex}`}
className="anchor-action-delete"
href="#foo"
onClick={(e) => {
e.preventDefault();
handleDelete(row);
}}>
thanks have a great day
There are 2 problems in your code:
req.params.id is meant for urls of the form /delete/:id which is obviously not your route, you should change it to req.query.id instead which matches query parameters in the url such as /delete?id=123.
The default type of _id is ObjectId, under the assumption you did not change this you need to cast your req.query.id which is type string to ObjectId.
It looks like you're using mongoose so here's mongoose syntax:
const mongoose = require("mongoose");
router.delete("/delete", (req, res) => {
Customer.findOneAndDelete({ _id: new mongoose.Types.ObjectId(req.query.id) }, (err, Customer) => {
if (!err) {
res.json({ msg: "customer deleted", deleted: Customer });
} else {
console.log("Error removing :" + err);
}
});
});
For nodejs native Mongo package:
import {ObjectId} from "mongodb";
...
new ObjectId(req.query.id)
I dont see you sent the id to the backend but you are trying to retrieve it from req.params.id try passing the id like "delete/:id" at the end of the link and specify this in the routes aswell.
if that doesnt fix try the below code this for routes
if nothing works check this, In the component you need to send the id(object id) but i see "row" what is the value of row? if the row value is not the id in the database then it wont delete. if this your issue try inspecting the code by keeping breakpoints or write a console.log() to check the value of "row" .
try {
const removedProject = await Customer.remove({
_id: req.params.id
})
res.json(removedProject)
} catch (err) {
res.json({
message: err
})
}
Related
Expense Tracker application : Nodejs, Mongodb
Trying to Create a function that will update only the passed fields from request inside an array of objects
Database Schema
const updateExpense = async (req, res) => {
try {
let db = mongo.getDb()
let { macro, micro, amount, note } = req.body;
let { username, id } = req.query
let expense = await db.collection("Expense").updateOne({ username: username, "expenses.expense_id": ObjectId(id) }, { $set: {
"expenses.$.macro": macro,
"expenses.$.micro": micro,
"expenses.$.amount": amount,
"expenses.$.note": note }
});
res.status(200).json({
message: "Expense Updated",
expense: expense
});
} catch (err) {
res.status(500).json({
message: err.message
});
}
}
The above function is replacing all other fields with null
If the user is passing only the micro field, then the other fields should remain the same and only the micro field should change and other fields should not change.
Need A MongoDB Query which will only change what is required based on the data passed in req
I think you must first fetch from the database with findOne then update that fields set in req.body, something like this:
const updateExpense = async (req, res) => {
try {
let db = mongo.getDb()
let { macro, micro, amount, note } = req.body;
let { username, id } = req.query
let expense = await db.collection("Expense").findOne({ username: username });
let special_ex = expense.expenses.find(ex => ex.expense_id === ObjectId(id);
special_ex.macro = macro ? macro : special_ex.macro;
special_ex.micro = micro ? micro : special_ex.micro;
/*
and so on ...
*/
await expense.update();
res.status(200).json({
message: "Expense Updated",
expense: expense
});
} catch (err) {
res.status(500).json({
message: err.message
});
}
}
I am creating URL Shortener Microservice application.I have a mongodb cluster that i save my all url links. I am successfully connect to database.I am making post request to save my posted url. Related code is here
app.post('/api/shorturl', (req, res) => {
const bodyUrl = req.body.url;
const something = dns.lookup(
urlParser.parse(bodyUrl).hostname,
(error, address) => {
if (!address) {
res.json({ error: 'Invalid URL' });
} else {
const url = new Url({ url: bodyUrl });
url.save((err, data) => {
res.json({
original_url: data.url,
short_url: data.id,
});
});
}
}
);
});
So, I can save my new url in database succesfully.Here also related cluster after post request
But my problem is with get request. I dont know why i cant find the url links by id. Here also my get request
app.get('/api/shorturl/:id', (req, res) => {
// const id = req.body.id;
Url.findById({ _id: req.body.id }, (err, data) => {
if (!data) {
res.json({ error: 'Invalid URL' });
} else {
res.redirect(data.url);
}
});
});
You need to either use:
Url.findOne({ _id: req.params.id }, (err, data) => {
if (!data) {
res.json({ error: 'Invalid URL' });
} else {
res.redirect(data.url);
}
});
or:
Url.findById(req.params.id, (err, data) => {
if (!data) {
res.json({ error: 'Invalid URL' });
} else {
res.redirect(data.url);
}
});
findOne takes an object as the argument (like you have).
findById just takes the ID as the argument.
You seem to be combining the two options.
Edit: I found another issue with your code, you are trying to pull the id from req.body.id, but in this case, you need to use req.params.id. The code in my post has been updated.
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'm updating a model inside an if condition but model not updating
exports.check_verification = (req, res) => {
var verifyCode=req.body.code;
console.log(vcode);
if(verifyCode=vcode){
const veryfy=User.updateOne({ _id:req.body.user_id }, { $set: { verify_status:"Registered"} },)
Promise.all([veryfy]).then(() => {
res.send("success");
}).catch((err) =>{
console.log(err);
})
}else{
console.log("fail");
res.send("fail");
}}
throw an error like this:
According to the error message req.body.user_id is not a string but instead is an object holding:
{ code: '...', user_id: '...' }
So what you can do is :
User.updateOne({ _id:req.body.user_id.user_id } //...
There might be something wrong with your request-model though.
I'm trying to update my MongoDB database using nodejs express and React. But instead of updating, the value is setting null.
It's updating well when I do the post request in postman or somewhere else.
In expressjs
//#route UPDATE api/todos/:id
app.post("/api/todos/:id", (req, res) => {
const { id } = req.params;
Todo.findOne({ _id: id })
.update({
completed: req.body.completed
})
.then(res.json({ updated: true }))
.catch(err => {
if (err) throw err;
});
});
In Reactjs
//completed: true/false <- updated
axios.post(`api/todos/${id}`, {
_id: id,
update: { title: updated }
});
I've tried .patch instead of .post, yet didn't solve the problem.
The expected result should be true/false, But it sets null.
Note: It happens not only for the true/false value but also for another value.
There are multiple things wrong with this code,
Wrong data capture:
You are sending {_id:id, update: {title: updated}
Which means in the req.body there will be two keys _id and updated
In your route it should be (refering Doc):
app.post("/api/todos/:id", (req, res) => {
const { _id, updated } = req.params;
Todo.update({ _id }, updated )
.then(()=>res.json({ updated: true }))
.catch(err => {
if (err) throw err;
});
});
Wrong Callback:
.then(res.json({ updated: true }))
This is wrong, because then expects function pointer. function(){}
In your case, res.json({ updated: true })() is being called because it thinks res.json({ updated: true }) is the function.
Change it to:
.then(()=>res.json({ updated: true }))