Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manipulate data object sequelize ORM (nodejs)

i have code like :

data = await photo.findOne({
    where : {id}
})

that return data

{
     "a" : 2,
     "b" : 5
}

i want to manipulate the data like insert some field

so i add properties :

data.c = data.a * data.b

i check in console.log the data added

{
     "a" : 2,
     "b" : 5,
     "c" " 10
}

but when i return to json

 return res.status(200).json({message: "success", data })

the data still like first { "a" : 2, "b" : 5 }

like image 387
Arif Fathurrohman Avatar asked Oct 16 '25 18:10

Arif Fathurrohman


1 Answers

The reason for your problem is

Finder methods are intended to query data from the database. They do not return plain objects but instead return model instances. Because finder methods return model instances you can call any model instance member on the result as described in the documentation for instances.

When you data.c = data.a * data.b do this, you are basically adding a property to the model instance not to the data object.

You can do something like

dataInstance = await photo.findOne({
    where : {id}
})
data = dataInstance.get({
   plain: true // Important
})
data.c = data.a * data.b;

Cheers. Don't forget to make the answer verified.

like image 135
Bharathvaj Ganesan Avatar answered Oct 18 '25 09:10

Bharathvaj Ganesan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!