4

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 }

3
  • When you use sequelize, you write to a table. So the first thing is to check the table structure. Do you have a column 'c'? Also how is the ORM schema and how do save the data? Commented Feb 6, 2018 at 19:04
  • no i dont have column 'c', but i wanna add some properties "c" to object "data" Commented Feb 6, 2018 at 19:20
  • I understand now what you are trying to do. I guess your problem is a timing issue. Something with asynchronous code that is not executed in the order you think. Commented Feb 6, 2018 at 20:04

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

wow i see, i'm misunterstanding for the model, but when i try , why return "dataInstance.get is not a function"
the answer is correct, thanks the reason i got error "dataInstance.get is not a function", because the data still in array and i use .findAll()
3

Finally I found answer after searching a lot. you should do something like this

const users = await db.users.findAll({})
.map(el => el.get({ plain: true })) // add this line to code

source :Github issue

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.