I want to delete otp automatically, from the database after 3 minutes. using sequelize.
I am trying this way
let delOtp = await Otp.destroy({ where: {createdAt: createdAt < '2021-12-20'}})
if (delOtp) {
res.status(200).json({ message: "otp deleted" })
} else {
res.status(401).json({ message: "not deleted", data: err})
}
It seems you need to change your condition to:
{ where: { createdAt: { [Op.gt]: '2021-12-20' } } }
Look at official documentation: Operators
Related
I'm working with sequelize v6 and I have an application uses apollo/server on backend and apollo/client on frontend.
Add, Remove and List records from a table are working well. But the Update method from Sequelize does'nt work for me.
Here's my Code in resolver.js (backend):
Mutation: {
async updateCustomer(_, { code_societe }, ...args) {
try {
const customer = await db.Customer.findByPk(code_societe);
if (customer) {
// DOESN'T WORK
await customer.update(args, { where: { code_societe: code_societe }});
await customer.save();
return customer;
}
throw new Error("Customer not found!")
}
catch (error) {
throw new Error(error.message);
}
},
}
I've tried many solutions but it doesn't work.
Thank you in advance!
I would like to suggest you use the transaction to run the query from Sequelize.
let transaction = await sequelize.transaction();
await customer.update(args, { where: { code_societe: code_societe, transaction: transaction } });
await transaction.commit();
references:
https://sequelize.org/v3/api/transaction/
https://sequelize.org/v3/api/model/#updatevalues-options-promisearrayaffectedcount-affectedrows
im using NEST JS and typeorm on MySql database. Update code:
const doneReport = await createQueryBuilder()
.update(ReportAd)
.set({ status: reportStatus.done })
.where('id = :id', { id: idReport })
.execute()
.then(result => {
console.log('RESULT', result);
return result;
});
When i update data using createQueryBuilder() and putted data is valid (id) i always get back result like:
RESULT UpdateResult { generatedMaps: [], raw: [], affected: 1 }
So, i cant recoginize if this record has been changed, or in this example 'status' hasn't changed. Only one option load object from db and compare objects before and after?
if I want throw invalid id error always ill always get back somethink like this?
RESULT UpdateResult { generatedMaps: [], raw: [], affected: 0 }
I have an array of objects which somewhat looks like this:
[
{
id: '5b29c08b-597c-460c-a3c7-ac8852b7a5dc',
option_text: 'njnj',
answer: false
},
{
id: '8ff5bda6-9335-495c-9c72-15ef258b899b',
option_text: 'jnjn',
answer: true
}
]
Here the answer column is inter-related like if any of the object's answer is set to true the other will come as false from frontend. So I've to update all the row associated with the referenced id.
What problem am facing is that the update query is not running but it is going inside the then block of the code instead of throwing error. Below is my code for the same:
// UPDATE Option
exports.updateOption = (req, res, next) => {
try {
console.log(req.body);
db.Option.update(req.body, {
where: { question_id: req.params.id }
}).then(() => {
console.log('A');
return res.status(200).send(errors.UPDATED_SUCESSFULLY);
}).catch(err => {
console.log('B');
return res.status(204).send(errors.INTERNAL_SERVER);
});
} catch(err) {
console.log('C');
return res.status(204).send(errors.INTERNAL_SERVER);
}
};
Sample Table Data for the same:
What I am thinking is that firstly to answer column false for all the rows associated with the same question_id and then update the particular row which has answer set to true.
But is this a good approach or anyone can suggest me some better solution ?
You should execute all updates in the same transaction (to avoid inconsistencies in DB):
sequelize.transaction(async transaction => {
const options = req.body;
for (const option of options) {
await db.Option.update(option, {
where: { question_id: req.params.id },
transaction
});
}
}).then(...
I have a route where a user can make a post, I want to create the post in one table and update a field in another table. I know that this can be done with back to back inserts, I am just not a hundred percent sure on how to do it. When a user makes a post, I want to create the post as well as update the boolean field hasPosts to true when they submit the post. Here is my route.
router.post('/create', function (req, res, next) {
let token = req.headers['jwt'];
if (token) {
authService.verifyUser(token).then(user => {
if (user) {
models.listings.findOrCreate({
where: { description: req.body.description },
defaults: {
quantity: req.body.quantity,
availability: req.body.availability,
requirements: req.body.requirements,
description: req.body.description,
org_id: user.id,
deleted: false,
}
}).spread(function(created, error) {
if(created) {
console.log(created)
res.status(200).json(created);
} else {
res.status(400).json(error)
}
})
} else {
res.status(500).json(error)
}
});
}
});
How would I go about piggy backing the request to update the users table field hasPosts to true?
Hey everyone so I am trying to update a monthly subscription to another monthly subscription in Braintree and prorate the charges. After reading their documentation I am stumped on how to do this effectively. When I go to update the subscription I get the following error message: 'ID has already been taken.'
router.put("/update-subscription", async (req, res, next) => {
try {
console.log("hit route");
if (!res.locals.user) {
throw { status: 403, message: "Not logged in." };
} else {
const { subscriptionId, selectedPlanName } = req.body;
const oldSubscriptionId = subscriptionId;
const selectedPlanId = selectedPlanName.replace(/\s/g, "_");
const userId = res.locals.user.id;
const [[userData]] = await database.query("call getUserByUserId(?)", [
userId
]);
const { braintreeId } = userData;
const { paymentMethods } = await gateway.customer.find("" + braintreeId);
const { token } = paymentMethods.find(p => p.default);
console.log("oldSubscriptionId", oldSubscriptionId);
console.log("selectedPlanId", selectedPlanId);
const subUpdateResponse = await gateway.subscription.update(
oldSubscriptionId,
{
id: selectedPlanId,
paymentMethodToken: token,
options: {
prorateCharges: true
}
}
);
console.log("subUpdateResponse", subUpdateResponse);
if (subUpdateResponse.success) {
res.send("Successfully updated plan");
} else {
throw { message: "An error occurred." };
}
}
} catch (error) {
next(error);
}
});
Heres the Log
subUpdateResponse ErrorResponse {
errors:
ValidationErrorsCollection {
validationErrors: {},
errorCollections: { subscription: [Object] } },
params:
{ id: 'SILVER_MONTHLY',
paymentMethodToken: 'krs2p5',
options: { prorateCharges: 'true' } },
message: 'ID has already been taken.',
success: false }
{ message: 'An error occurred.' }
I understand that the 'SILVER_MONTHLY' ID is already used I mean I am trying to update from one subscription to the other obviously the one I am trying to update to has already been used. Again all I am trying to do is update from the subscription the user is already on to the subscription the user picked to update to. Any help here would be great. Thanks
Full disclosure, I work at Braintree. If you have any further questions, I recommend contacting Support
You are passing the plan ID in the incorrect parameter. The id parameter can be used for a new subscription ID that you'd like to have. To update to a different plan, you'll need to pass a planId parameter, which represents the plan you'd like to update them to.
I also noticed you are passing a paymentMethodToken parameter. This is to be used only if you're updating the payment method token. If that's what you intended, carry on! Otherwise, you do not need to pass this parameter in your update request.
As an example, if you wanted to update the plan and keep the same payment method token, your request may look something like this:
const subUpdateResponse = await gateway.subscription.update(
oldSubscriptionId,
{
planId: selectedPlanId,
options: {
prorateCharges: true
}
}
);