Search code examples
javascriptes6-promisebookshelf.js

Variable from promise remains unchanged on Bookshelf save().then()


I have the following code:

User.forge(req.body)
                .save()
                .then((model) => {
                    model.id = undefined;
                    console.log(JSON.stringify({data: model}));
                    res.json({data: model})
                })

which prints this into console:

{"data":{"name":"Test User","username":"test_usr","role_id":1,"id":54}}

Why it is not changing the value of model.id even on Promise.then?


Solution

  • The id you are touching is just a convenience attribute -- it is always named id no matter the real model id attribute name is. The model attributes, that are used by stringify, are taken from the attributes object within the model.

    So you could just do model.attributes.id = undefined, but this approach is not recommended because it relies on Bookshelf internals.

    The right approach is to use model.set('id', undefined) instead.