Skip to content

Save/update model with association #5471

Closed

Description

@carrbrpoa

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?

name_required

exception

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

  1. mickhansen commented on Feb 23, 2016

    @mickhansen
    Contributor

    When using include with 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.

  2. carrbrpoa commented on Feb 23, 2016

    @carrbrpoa
    Author

    Thanks for the reply @mickhansen. Here it goes:

    Executing (d99b3370-d54a-42e8-bb88-c753e181be0a): START TRANSACTION;
    Executing (d99b3370-d54a-42e8-bb88-c753e181be0a): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
    Executing (d99b3370-d54a-42e8-bb88-c753e181be0a): UPDATE "projects" SET "id"=1,"archived"=false,"name"='The Ultra Project',"updatedAt"='2016-02-23 12:07:32.726
    +00:00' WHERE "id" = 1
    Executing (d99b3370-d54a-42e8-bb88-c753e181be0a): UPDATE "sprints" SET "id"=1,"name"='Sprint 1',"start"='2016-02-24 03:00:00.000 +00:00',"end"='2016-03-02 03:00
    :00.000 +00:00',"projectId"=1,"updatedAt"='2016-02-23 12:07:32.730 +00:00' WHERE "id" = 1
    Unhandled rejection SequelizeValidationError: notNull Violation: name cannot be null
        at C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\lib\instance-validator.js:74:14
        at tryCatcher (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\util.js:11:23)
        at Promise._settlePromiseFromHandler (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.j
    s:491:31)
        at Promise._settlePromise (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.js:548:18)
        at Promise._settlePromise0 (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.js:593:10)
        at Promise._settlePromises (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.js:676:18)
        at Promise._fulfill (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.js:617:18)
        at PromiseArray._resolve (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise_array.js:125:
    19)
        at PromiseArray._promiseFulfilled (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise_arra
    y.js:143:14)
        at Promise._settlePromise (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.js:553:26)
        at Promise._settlePromise0 (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.js:593:10)
        at Promise._settlePromises (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\promise.js:676:18)
        at Async._drainQueue (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\async.js:125:16)
        at Async._drainQueues (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\release\async.js:135:10)
        at Immediate.Async.drainQueues [as _onImmediate] (C:\cesar.ribeiro\Trabalho\workspace\manage-lite-rest\node_modules\sequelize\node_modules\bluebird\js\relea
    se\async.js:16:14)
        at processImmediate [as _immediateCallback] (timers.js:358:17)
    
    Executing (d99b3370-d54a-42e8-bb88-c753e181be0a): COMMIT;
    

    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 upsert instead of save/create logic.

    The models involved:

    var Project = database.define('projects', {
            name : {
                type : Sequelize.STRING,
                allowNull : false,
                unique : true
            },
            archived : {
                type : Sequelize.BOOLEAN,
                allowNull : false,
                defaultValue : false
            }
        });
    
    var Sprint = database.define('sprints', {
            name : {
                type : Sequelize.STRING,
                allowNull : false
            },
            start : {
                type : Sequelize.DATE
            },
            end : {
                type : Sequelize.DATE
            }
        });
    
    Project.hasMany(Sprint, {
        as : 'sprints'
    });
    Sprint.belongsTo(Project);

    PS: I have no requires for Promise I'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

  3. mistercorea commented on Apr 25, 2016

    @mistercorea

    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

    Model.create(obj).then(function(model){
        model.createModel2(obj)
    },function(err){next(err)
    })
    

    What I would like to do is

    Model.build(obj).validate().success(
        function(){Model2.build(obj).validate().success(function(){
            Model.save(function(m){
                Model2.save(function(m2){
                    m2.setModel(m)
                })
            })
        }).error(function(e){next(e))
    }).error(function(e){next(e))
    

    If there is better way to do this I would love to know.

  4. mickhansen commented on Apr 26, 2016

    @mickhansen
    Contributor

    @mistercorea save doesnt take a callback like that, we use promises

  5. mistercorea commented on Apr 26, 2016

    @mistercorea

    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??

  6. mickhansen commented on Apr 26, 2016

    @mickhansen
    Contributor

    @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).

  7. ybrodsky commented on Apr 28, 2016

    @ybrodsky

    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.???

  8. mistercorea commented on Apr 28, 2016

    @mistercorea

    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?

  9. mistercorea commented on May 2, 2016

    @mistercorea

    @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

    data[0].dataValues.id = data[1].dataValues.id
    

    where data is array of the models.
    at the end i am doing something like

    data.forEach(function(modelObj){
          savedObjs.push(modelObj.save())
    })
    Promise.all(savedObjs).then(function(){
          return res.send('OK');
    })
    

    Is this possible? because i cant find any documentation or people using build() to build associated model objects.

  10. mickhansen commented on May 3, 2016

    @mickhansen
    Contributor

    @mistercorea Validation happens automatically on create, why not just use a transaction?

  11. mistercorea commented on May 3, 2016

    @mistercorea

    @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.

    arrayObjs.forEach(function(obj){
        let sqlizeObj = obj.build(input);
        retArrayObjs.push(sqlizeObj);
        errArrayObjs.push(sqlizeObj.validate());
      })
    

    No one has this problem?

  12. mickhansen commented on May 3, 2016

    @mickhansen
    Contributor

    @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)

  13. mistercorea commented on May 3, 2016

    @mistercorea

    @mickhansen I am little confused.

    sequlize.transaction(function(t){
        return Model1.create({JSON}),{transaction:t})
        .then(function(m1){
            return m1.createM2({JSON},{transaction:t})
        })
    }).then(function(result){})
    .catcH(function(err){})
    

    while reflect uses Promises from each model.

    So i can pass each one synchronized way? then get result?

  14. mickhansen commented on May 3, 2016

    @mickhansen
    Contributor

    @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?

  15. mistercorea commented on May 3, 2016

    @mistercorea

    @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.

  16. 15 remaining items

  17. papb commented on Sep 14, 2019

    @papb
    Member

    Why is not this backed into sequelize itself?, it wont be difficult to just add a recursive description of update behaviour for n-ary associations and a transaction tag, among others.

    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!!

  18. mohammednadeem772 commented on Dec 31, 2019

    @mohammednadeem772

    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);
    });

  19. self-assigned this
    on Jan 7, 2020
  20. added
    docs
    on Jan 7, 2020
  21. papb commented on Jan 9, 2020

    @papb
    Member

    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.

  22. added
    status: wip
    and removed on Jan 9, 2020
  23. removed
    status: wip
    on Jan 15, 2020
  24. papb commented on Jan 16, 2020

    @papb
    Member

    This has been centralized in #11836

  25. pss4281 commented on Feb 10, 2020

    @pss4281

    Why is not this backed into sequelize itself?, it wont be difficult to just add a recursive description of update behaviour for n-ary associations and a transaction tag, among others.

    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!!

    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

  26. sergiomendonca commented on Jul 22, 2020

    @sergiomendonca

    Why is not this backed into sequelize itself?, it wont be difficult to just add a recursive description of update behaviour for n-ary associations and a transaction tag, among others.

    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!!

    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

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

docs

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions