Repository navigation
Description
I'm implementing some RESTful stuff and now trying to update a model which it's children can be new or not:
router.put('/projects/:projectId', function (req, res, next) {
models.database.transaction().then(function (t) {
var project = models.Project.build(req.body, {
isNewRecord : false,
include : [{
model : models.Sprint,
as : 'sprints'
}
]
});
Promise.all([project.save({
transaction : t
}), project.sprints.map(function (sprint) {
if (sprint.getDataValue('id')) {
return sprint.save({
transaction : t
});
} else {
sprint.projectId = project.id;
return models.Sprint.create(sprint, {
transaction : t
});
}
})]).then(function (response) {
t.commit(); //Debug enters here...
return res.json(response);
}, function (err) {
t.rollback(); //...not here
if (err.message === 'Validation error') {
res.status(403);
res.send(err);
} else {
next(err);
}
});
});
});So, assuming I pass one sprint with id and another without it, I was expecting an update in the first one and an insert in the second, but what I see is a notNull Violation: name cannot be null
supposedly from the sprint that needs to be inserted - which is not the case, the name is there (I'm using node-inspector); also, it doesn't enter in the callback error function, but it actually commits the transaction, that apparently updates project and the first (not new) sprint.
There's a better way to do what I'm trying to achieve? Did something wrong?
PS1: The same happens with upsert command, but this way it seems to also complains about the first sprint's name.
PS2: The same happens without transaction.
Thanks


Activity
mickhansen commentedon Feb 23, 2016
When using
includewith build and then save you'll trigger the the nested creation code path. After that you then yourself save and create (duplicates most likely).I can't specifically say what's going on here, too much going on.
Try including the stack as text and highlighting that line so we can see where the error starts.
carrbrpoa commentedon Feb 23, 2016
Thanks for the reply @mickhansen. Here it goes:
Seems that the error is popped when all the promises are resolved, or something like that.
It's all the stack. In the printscreen before, you see two identical because I got them when tried with
upsertinstead of save/create logic.The models involved:
PS: I have no requires for
PromiseI'm using in my code above because I understood it's sequelize's built-in.Please tell me if you need more info.
Thanks in advance
mistercorea commentedon Apr 25, 2016
I am stuck on similar issue.
When i tried to create joined model, It will validate and create the first model then it will invalidate on second one.
Now If i am trying to create again it will fail on first model's validation because it already created the fist data model and unique column validation will throw an error.
For example
What I would like to do is
If there is better way to do this I would love to know.
mickhansen commentedon Apr 26, 2016
@mistercorea
savedoesnt take a callback like that, we use promisesmistercorea commentedon Apr 26, 2016
ahhhhhh THANKS !!!
below code works.
Model.build(obj).validate().then(function(e){console.log(e)})
But shouldn't be catch instead of using then? because validation fails then it will throw an error??
mickhansen commentedon Apr 26, 2016
@mistercorea validate will return validation errors unless it failed executing, you can use hookValidate for it to throw when theres a validation error (not completely logical i know).
ybrodsky commentedon Apr 28, 2016
Isn't there any way to do this somehow simpler?
For example in my case.
model City hasMany CitiesDescription
So I can do:
models.City.create(data, {include: [models.CitiesDescription]})This works great and as expected.
Now, updating is a different issue.
I have implemented a solution similar to @carrbrpoa and it works. The problem is that if my data doesn't include CitiesDescription, it breaks.
Anyway, it looks way too far-fetched... Isn't there a way to do something like this:
models.City.update(data, { where: { id: recordID }, include: [models.CitiesDescription] })So that it updates whether my data contains an array for CitiesDescriptions or not and will update those records that should be updated and create those that should, inside that array.???
mistercorea commentedon Apr 28, 2016
So is there anyway do a validation before I create a row to associated table?
For example, if first validation passes then it will create a row by Model.create() then if associated Model2 failed to validate then createModel2 will not get written. Now i have half written and half not written.
That is why i tried to validate with build().validate() but id wont associated to each other.
I have to hard code the relationship. Is there a better way to do this, with or without using non-persistent instance?
mistercorea commentedon May 2, 2016
@mickhansen I have a quick question if I want to build, validate then save two associated models.
I have to manually assign the foreign key ID to associate
where data is array of the models.
at the end i am doing something like
Is this possible? because i cant find any documentation or people using build() to build associated model objects.
mickhansen commentedon May 3, 2016
@mistercorea Validation happens automatically on create, why not just use a transaction?
mistercorea commentedon May 3, 2016
@mickhansen I would like to know all the errors from multiple models, instead of tell me some error from one model then if I fixed the error then it tell me other errors from the other model.
I used first example from http://docs.sequelizejs.com/en/latest/api/transaction/ .
For me solution was some what troublesome. I build each objects then to validation.
If there is any errors i dont save it.
No one has this problem?
mickhansen commentedon May 3, 2016
@mistercorea Your issue is with control flow, not with Sequelize - So finding others with the exact same problem is likely hard :)
Promise join method generally reject on the first error, but you could possible looking at using
hookValidate+settle(http://bluebirdjs.com/docs/api/reflect.html)mistercorea commentedon May 3, 2016
@mickhansen I am little confused.
while reflect uses Promises from each model.
So i can pass each one synchronized way? then get result?
mickhansen commentedon May 3, 2016
@mistercorea Almost nothing in Sequelize is sync. Not sure how the piece of transaction code you listed is related, didn't you just say you wanted all errors?
mistercorea commentedon May 3, 2016
@mickhansen yes, but if i get an error from Model1 I wont get error from Model2.
I think transaction is the right way to do it but I needs to validate both models and tell me what what failed.
settle/reflect needs to have their own Promise object returned.
So I cant do m1.createModel2 because that has to have m1 object return from first promise.
I am not sure how people do validation for associated models and save it all together.
I have create my own way but it's not pretty or organized.
Thank you for you time for this. This is first project i am doing with nodeJS and I am kinda circling because i dont know what i dont know.
15 remaining items
papb commentedon Sep 14, 2019
I disagree. It is difficult (relatively)... Doing nested updates is definitely nontrivial because deciding whether the nested objects are new or just changed from one that already exists is nontrivial. To me, at least.
If anyone is willing to submit a PR that would be great. However, before doing that please make sure you define what behavior are you exactly going to implement and let me know so I can agree with it first, in order to not waste anyone's time.
Thanks!!
mohammednadeem772 commentedon Dec 31, 2019
Hello guys,
Is there is a way to use include in PUT method like this
const newProduct = req.body;
db.products.update(newProduct, where: { id: req.params.id },{
include: [
{
model: db.variants,
as: 'variants' ,
},
],}).then(product => {
res.json(product);
}).catch((err) => {
res.status(500).send(err);
});
papb commentedon Jan 9, 2020
After further investigation, this is indeed not possible currently, the issue #6808 tracks the feature request to enable this.
I will leave this open for now simply as a documentation issue, in order to make it clear in the documentation that this is currently not supported. The feature request itself should be tracked in #6808.
papb commentedon Jan 16, 2020
This has been centralized in #11836
pss4281 commentedon Feb 10, 2020
I'd argue this,
it's pretty simple to implement,
just check if the nested object has id property. If it does - it's an existing record and we should be doing updates, otherwise - new record and we do insert.
That's exactly how Rails is doing it.
so
{ "firstName": "John", "Addresses": [ {"id": 1, "streetName": "Church str"}, {"streetName": "Brookers lane"} ] }assuming User.hasMany(Address)
the first one should be updated and the second one inserted
sergiomendonca commentedon Jul 22, 2020
no way its trivial. You are talking about a 1-1 association. Try it for any associations in any levels. Example: Customer > Address > Address Phone . Customer-Adress: 1-n,Adress - Adress Phone: 1-n . I think it is very important in sequelize to have this, but its not trivial.