10

the code like this:

(function () {
    var tag = models.Tag.build({ create_time: new Date(), is_hot: '0', is_lock: '0', name: 'Nodejs' });
    tag.save();
    console.log(tag.dataValues);
    tag.name = "npm";
    tag.save();
    console.log(tag.dataValues);
    tag = models.Tag.build({ create_time: new Date(), is_hot: '0', is_lock: '0', name: 'webpack' });
    tag.save();
    console.log(tag.dataValues);
})();

the result is: the result

in my first eys,the result maybe:

Executing (default): INSERT INTO `t_tag` (`id`,`name`,`create_time`,`is_hot`,`is_lock`,`is_delete`) VALUES (NULL,'Nodejs','2016-12-23 03:09:23','0','0','0');
Executing (default): INSERT INTO `t_tag` (`id`,`name`,`create_time`,`is_hot`,`is_lock`,`is_delete`) VALUES (NULL,'npm','2016-12-23 03:09:23','0','0','0');
Executing (default): INSERT INTO `t_tag` (`id`,`name`,`create_time`,`is_hot`,`is_lock`,`is_delete`) VALUES (NULL,'webpack','2016-12-23 03:09:26','0','0','0');

what causes that ? why the "npm" record insert double time?

4
  • to avoid that just build another model for npm Commented Dec 23, 2016 at 3:46
  • yeah,is can solve the problem。but why the npminsert double time Commented Dec 23, 2016 at 3:52
  • when you tag.name = "npm"; it doesn't really change the value of column name in your build Tag and remember you try tag.save() again which it will just insert the previous value again that's why it insert twice Commented Dec 23, 2016 at 3:55
  • when the code like (function () { var tag = models.Tag.build({ create_time: new Date(), is_hot: '0', is_lock: '0', name: 'Nodejs' }); console.log(tag.dataValues); tag.save(); tag.name = "npm"; })();, it also insert the npm. TnT Commented Dec 23, 2016 at 5:39

1 Answer 1

5

Sequelize functions run asynchronously. save returns a promise, which you can .then() off of to ensure that you're picking up after the SQL call has gone through. Since you're not doing that, the first save hasn't persisted by the time you change tag.name to "npm" and therefore "npm" is inserted twice (notice how all three console.log calls execute before anything else happens -- this is another sign that you're not doing async properly). Fix your flow control to work with the promises and you won't have this problem.

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

2 Comments

you mean: when the code run tag.name ="npm", the first tag.save() didn't complete? Is it right?
Yes, the first tag.save() went through after tag.name = "npm" because you didn't wait for the asynchronous save to finish. The examples in the Sequelize docs show how to use model.save().then(do the next thing).

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.