Node + Sequelize:如何在添加之前检查项目是否存在?(异步混淆)

waf*_*ffl 16 javascript asynchronous node.js sequelize.js async.js

不幸的是,我对节点很新,并且在节点的异步/同步执行方面遇到了一些混乱.

我正在使用node,sequelize with sqlite和async.js.

我有一系列Articles,每个都有一些Authors.

对于每Authors一个Article,我想检查是否Author存在.如果没有,请创建它.

问题是,在初始运行时,正在创建重复的作者,我假设由于异步功能导致检查存在的问题.

例如,使用数组: authors = ['A. Test', 'B. Test', 'C. Test', 'A. Test']

和代码:

async.each(authors, function(item, callback){
    Author.sync().then(function(){
      Author.count({ where: {name: item.trim()} }).then(function(count){
        if (count != 0) {
          console.log('Author already exists')
        } else {
          console.log('Creating author...')
          Author.create({
            name: item.trim()
          })
        }
      })
    })
  })
Run Code Online (Sandbox Code Playgroud)

在第一次运行时,将创建一个表:

ID | name
------------
0  | A. Test
1  | B. Test
2  | C. Test
3  | A. Test
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我似乎错过了Node中异步与同步执行的基本概念.

(我也尝试过async.eachSeries,它应该是串行执行而不是并行执行?)

编辑:稍微重构,但仍然创建重复

async.eachSeries(authors, function(authorName, callback){
    Author.findOne({ where: {name: authorName.trim()} }).
    then(function(author){
      if (author) {
        // Author exists...
        callback()
      } else {
        // Author does not exist...
        Author.create({
          name: authorName.trim()
        }).then(function(author){
          callback()
        })
      }
    })
  })
Run Code Online (Sandbox Code Playgroud)

Jos*_*a F 16

Author.count不是真的需要,除非你需要计数.请参阅findOrCreate().

有了findOrCreate()你可以有以下几种.(编辑trex005的代码片段)

async.eachSeries(authors, function(item, callback) {
  Author.sync().then(function() {
    Author.findOrCreate({
      where: {
        name: item.trim()
      },
      defaults: { // set the default properties if it doesn't exist
        name: item.trim()
      }
    }).then(function(result) {
      var author = result[0], // the instance of the author
        created = result[1]; // boolean stating if it was created or not

      if (!created) { // false if author already exists and was not created.
        console.log('Author already exists');
      }

      console.log('Created author...');
      callback();
    });
  })
})
Run Code Online (Sandbox Code Playgroud)


tre*_*005 0

将您的每个更改为eachSeries并实际调用回调,您应该是黄金。

async.eachSeries(authors, function(item, callback){
    Author.sync().then(function(){
      Author.count({ where: {name: item.trim()} }).then(function(count){
        if (count != 0) {
          console.log('Author already exists')
          callback(); //assuming you want it to keep looping, if not use callback(new Error("Author already exists"))
        } else {
          console.log('Creating author...')
          Author.create({
            name: item.trim()
          }).then(function(author){
            callback();
          })
        }
      })
    })
  })
Run Code Online (Sandbox Code Playgroud)