Convert MySQL update query into sequelize query - mysql

UPDATE `users` SET tempToken=tempToken-"5" WHERE `id`="1"
How can I write this query into sequelize query.

For an async function, this is how you would do it, assuming you've set up your User model:
myFunction: async (req, res) => {
var tempToken = req.body.tempToken // Put whatever your data source is here for tempToken
var newValue = tempToken - 5
try {
await User.update({
tempToken: newValue
},
{
where: [{
id: 1
}]
})
res.status(200).send();
}
catch (error) {
res.status(500).send(error);
}
}
or
myFunction: async (req, res) => {
try {
const user = User.findOne({
where: {
id: 1
}
})
await user.update({
tempToken: user.tempToken - 5
})
res.status(200).send();
}
catch (error) {
res.status(500).send(error);
}
}
Also, don't forget to 'require' the user model in the .js file that you use this function in.

Related

Mongoose updating and fetching in the same request

I have the following mongoose "update" path:
app.put('/update', async (req, res) => {
const newTaskName = req.body.todoName
const newDays = req.body.days
const id = req.body.id
try {
await TodoModel.findById(id, async (err, updatedTodo) => {
updatedTodo.todoName = newTaskName
updatedTodo.daysToDo = newDays
await updatedTodo.save()
res.send("updated")
})
} catch(err) {
console.log(err)
}
})
Separately I have a path that returns all data from the Mongo table:
app.get('/read', async (req, res) => {
TodoModel.find({}, (err, result) => {
if (err) {
res.send(err)
}
res.send(result)
})
})
How can I both update and send back the full updated list within the response?
Separate question, not necessary to answer, but would be nice - perhaps this approach is all wrong? some background:
In my MERN app I am calling to add an item to a list and then want to immediately render the updated list as currently read from the database, since I don't want to assume the insertion was successful
I tried using some asynchronous workarounds with no luck
Fixed!
Upon further inspection of Mongoose documentation, I found that by using the findOneAndUpdate method instead of findById, I am able to utilize a callback that will return the updated item:
app.put('/update', async (req, res) => {
const id = req.body.id
let updateSet = req.body
delete updateSet.id
try {
ShoppingModel.findOneAndUpdate({ _id: id }, { $set: updateSet }, { new: true }, (err, doc) => {
if (err) return console.log(err)
res.send(doc)
})
} catch (err) {
console.log(err)
}
})

How do I fetch just one object from the mySQL database?

I want to get and res.send user_image from the table. I tried to use attributes: ['user_image'], but it does not work. Is there any other keyword or style to fetch just one object?
const router = require('express').Router();
const db = require('../models');
router.get('/image/:user_id', (req, res) => {
try {
db.Customer.findAll({
where: {
user_id: req.params.user_id,
attributes: ['user_image'],
},
}).then((user) => res.send(user));
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;

Sequelize showing error: Unexpected token u in JSON at position 0

I am trying to update a record in mysql database using sequelize but it is not working.
I am getting this error
Unexpected token u in JSON at position 0
Model
module.exports = sequelize.define("branches", {
address: Sequelize.TEXT(),
company: Sequelize.STRING(),
codeConfig: {
type: Sequelize.STRING,
allowNull: false,
get: function () {
return JSON.parse(this.getDataValue('codeConfig'));
},
set: function (val) {
return this.setDataValue('codeConfig', JSON.stringify(val));
}
},
});
Update function
router.put('/:id', async (req, res) => {
const { address, company} = req.body;
try {
const branches = await Branches.findOne({ where: { code: req.params.id } });
if (!branches) return res.json({ msg: "Branch Not Found" });
Branches.update({ "address": "No. 10 distreet street" }, {
where: {
code: "WHJ5uBdriI"
}
}).then(function (newBranch) {
return res.json({ msg: "Updated" });
});
} catch (error) {
console.error(error.message);
res.status(500).send("Server Error");
}
});
Error output
Add autoJsonMap: false, to your sequelize's dialectOptions
Example:
let sequelize = new Sequelize(DATABASE, USER, PASSWORD, {
// some other options
dialectOptions: {
autoJsonMap: false,
}
});
Reference:
https://github.com/sequelize/sequelize/issues/12583
i have noticed that before sequelize make a field update, it fetches through all fields, and then execute a getter function if exist, so for that i added an if check inside a getter, here is the code now the model.update working:
get: function () {
if(this.getDataValue('codeConfig') !== undefined){
/// appentely sequelize tried to parse the value of 'codeConfig' but its undefined since you are updating only address field.
return JSON.parse(this.getDataValue('codeConfig'));
}
},

Query inside foreach Node.js Promis

i put query inside for each on promise. I am trying to query a mysql database twice, the second time, multiple times for each result from the first time but I am unable to work out how to wait for the result from the second query before continuing
i want the output like this :
{
"data":[
{
"name":"Title result",
"images":[
{
"id":1,
"place_id":705,
"path_image":"http://3.bp.blogspot.com/-iwF-ImFpzvk/T6fKhC6F7YI/AAAAAAAAARA/FyKpNcDsP8M/s1600/asd2e1.jpg"
},
{
"id":2,
"place_id":705,
"path_image":"https://asrt.bp.com/data/photo/2014/07/22/sddrfr2.jpg",
}
]
}
]
}
but i get only like this :
{
"data":[
{
"name":"Title result",
"images":[]
}
and this is my code:
return new Promise((resolve, reject) => {
const { connection, errorHandler } = deps;
let arrayData = [];
let imageData = [];
connection.query(
"SELECT * FROM places WHERE id = 705",
(error, rows, results) => {
rows.forEach((row) => {
connection.query(
"SELECT * FROM place_gallery WHERE place_id = 705",
(error, rows, results) => {
imageData = rows;
}
)
arrayData.push({ name: row.title, images: imageData })
});
if (error) {
errorHandler(error, "failed", reject);
return false;
}
resolve({ data: arrayData });
}
);
})
},
how to solve this?
try this, another way instated of creating dbcall function you can convert the query callback to promise using util.promisify()
const dbcall = (query) => {
return new Promise((resolve, reject) => {
connection.query(
query,
(error, rows, results) => {
if (error) return reject(error);
return resolve(rows);
});
});
};
const somefunc = async () => {
const {
connection,
errorHandler
} = deps;
let arrayData = [];
try {
const rows = await dbcall("SELECT * FROM places WHERE id = 705");
rows.forEach(async (row) => {
const imageData = await dbcall("SELECT * FROM place_gallery WHERE place_id = 705");
arrayData.push({
name: row.title,
images: imageData
});
});
} catch (error) {
console.log(error);
}
return arrayData;
}

Incorrect response after iteration inside for-loop for findById()

I had created 2 tables named: groupusermaps and groups. From groupusermaps i am fetching all the groupId and these groupId I am passing in findById() method to fetch all the details related to that groupId inside the for loop.
here is my method in service:
getAllGroupsByUserId(userId, callback) {
var arr = [];
return sequelize.transaction().then(function(t) {
return groupUserMapModel.GroupUserMap.findAll({
where: {
userId: userId
},
transaction: t
}).then((allGroupsByUserId) => {//from findAll i am getting 2, 1, 4
groupId
for (var p in allGroupsByUserId) {
return
groupModel.Group.findById(allGroupsByUserId[p].groupId, { transaction: t
}).then((group) => {
arr.push(
JSON.stringify(group)
);
});
}
}).then(() => {
callback(arr);
});
});
}
my controller code:
router.get('/controllers/getGroups/user/:userId/groups', (req, res) => {
groupService.getAllGroupsByUserId((req.params.userId), (result) => {
log.info('Group list: ' + JSON.stringify(result));
});
res.send('Fetched all group list');
});
But I am getting an empty array as response from the controller on the console. Is there any way to fix this issue?
groupUserMapModel.GroupUserMap.findAll({
where: {
userId: userId
},
include:[{
model:groupModel
}]
})
.then((results) => {
console.log(results);
})
.catch(err=>{
console.log(err);
})
// provided that groupUserMapModel associated to groupModel
groupUserMapModel.associate = models => {
groupUserMapModel.belongsTo(models.groupModel, {foreignKey: groupId})
}
for more info read about sequelize association