how do I update an object in Sequelize - node.js

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);
};
}

Related

NodeJS does not returning status code but changes database

my code below works just fine and updates or creates documents, but does not return status code 200 it just waits without any return value, any idea why this is happening
exports.flagUser = async (req, res) => {
try {
const user = await FlaggedUser.findOne({ userId: req.body.userId });
if (user) {
if (user.flaggedBy.includes(req.body.flaggedBy.toString())) {
print("error");
return res.status(500);
} else {
console.log("user found");
await user.updateOne({
$inc: { flagCount: 1 },
$addToSet: { flaggedBy: req.body.flaggedBy },
});
return res.status(200);
}
} else {
const flaggedUser = new FlaggedUser({
_id: new mongoose.Types.ObjectId(),
userId: req.body.userId,
flagCount: 1,
flaggedBy: [req.body.flaggedBy],
});
await flaggedUser.save();
console.log("flag");
return res.status(200);
}
} catch (error) {
console.log(error);
return res.status(500).json({
...error,
});
}
};
If you want to send just status codes you need to write res.status(num).send(); or res.status(num).end();. Here is the doc to read more up on this http://expressjs.com/en/api.html

findOneAndDelete Mongoose not working MERN stack

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
})
}

Issue with update in Mongoose

I have wrote a simple Update function. Its working fine for some minutes and then again its not working. Where I am going wrong? Please help me. I use PUT as my method.
code
accept = (req, res) => {
this._model.update({
user: new mongoose.Types.ObjectId(req.params.uid)
}, {
$set: {
status: 'active'
}
}, (err, obj) => {
if (err || !obj) {
res.send(err);
} else {
res.send(obj);
}
});
}
Model
{
"_id":"5d3189a00789e24a23438a0d",
"status":"pending",
"user":ObjectId("5d3189a00789e24a23438a0d"),
"code":"CT-123-345-234-233-423344",
"created_Date":"2019-07-19T09:13:04.297Z",
"updated_Date":"2019-07-19T09:13:04.297Z",
"__v":0
}
Request
api.abc.com/api/accept/5d3189a00789e24a23438a0d
Sometime it is returing values and sometime null.
You can use the following code to ensure the model is tied to a connection. This could be an issue of connection to the database.
const config = require('./config');
console.log('config.database.url', config.database.url);
return mongoose.createConnection(config.database.url, {
useMongoClient: true
})
.then((connection) => {
// associate model with connection
User = connection.model('User', UserSchema);
const user = new User({
email: 'someuser#somedomain.com',
password: 'xxxxx'
});
const prom = user.update();
// Displays: 'promise: Promise { <pending> }'
console.log('promise:', prom);
return prom
.then((result) => {
// Don't see this output
console.log('result:', result);
})
.catch((error) => {
// Don't see this output either
console.log('error:', error);
});
})
.catch((error) => {
console.log(error);
});
I think you need to use promise or async/await, try this
accept = async (req, res) => {
try {
const result = await this._model.update({
user: new mongoose.Types.ObjectId(req.params.uid)
}, {
$set: {
status: 'active'
}
});
return res.send(result);
} catch (e) {
return res.send(e);
}
};

User.destroy is not a function

I use the oracle-sage library. And when I want to delete a record, an error occurs.
{
"success": false,
"message": "User.destroy is not a function"
}
How can fix this?
const User = require('../models/User')
const errorHandler = require('../utils/errorHandler')
module.exports.remove = async function (req, res) {
try {
await User.destroy({
USER_ID: req.params.USER_ID
})
res.status(200).json({
message: 'User deleted.'
})
} catch (e) {
errorHandler(res, e)
}
}
Probably .destroy is not a static method, needs an instantiated object. You can try to get the user object first then destroy it.
try {
let user = await User.findOne({ USER_ID: req.params.USER_ID});
user.destroy().then(function(){
res.status(200).json({
message: 'User deleted.'
})
});
} catch (e) {
errorHandler(res, e)
}
Another way to implement destroy method is as below
const deleteUser = async (req,res) => {
console.log('Deleting User by Id')
const userId = await req.params.id
const user = await User.destroy({
where:{
id : userId
},
raw:true
}).catch(error=>console.log(error))

Wait for Mongoose to resolve data before returning

I'm trying to loop through this array and append user objects to each object inside. How do I wait for each of them to complete before returning the JSON to the client?
Match.find()
.or([{ user_id: req.user._id }, { second_user_id: req.user._id }])
.exec((err, result) => {
if (err) {
return res.sendStatus(500);
}
result.map(async match => {
match.user = await User.findById(req.user._id).exec();
});
return res.json({ matches: result });
});
In this case the array is returned to the client before Mongoose has a chance to resolve the findById queries.
Try this and let me know how it goes:
Match.find()
.or([{ user_id: req.user._id }, { second_user_id: req.user._id }])
.exec(async(err, result) => {
if (err) {
return res.sendStatus(500);
}
const results = await Promise.all(result.map(async match => {
match.user = await User.findById(req.user._id).exec();
}));
return res.json({ matches: results });
});

Resources