【问题标题】:Find or create with SequelizeJS使用 SequelizeJS 查找或创建
【发布时间】:2013-05-26 17:03:20
【问题描述】:

我尝试使用 SequelizeJS 的“findOrCreate”功能,但它不起作用。

变量“created”是“undefined”,所以不知道为什么,因为它是SequelizeJS使用的变量...

for( var i = 0; i < tags.length; i++ ){
    global.db.Tag.findOrCreate({name: tags[i]}).success( function(tag, created){
        if( created ){
            global.db.PostTag.create({
                PostId: id,
                TagId: tag.id
            });
        }
    });
}

【问题讨论】:

  • 您使用的是哪个版本?我相信更改可能尚未发布到 npm,所以您可以尝试使用来自 github.com/sequelize/sequelize 的最新版本吗?

标签: node.js express sequelize.js


【解决方案1】:

我们昨天遇到了这个问题,我们能够解决它:

Tag.findOrCreate({
     where: { condition: value },
     // in the event that it is not found
     defaults: { /* properties of the model to create */ }
 })
     .then(tag => res.send(tag))
     .catch(err => res.send(err))`

返回:

{
    {
        /* tagProperties */
    },
    /* true if the tag was created
       false if the tag was found */
}

【讨论】:

  • 欢迎来到 Stack Overflow。在 Stack Overflow 上不鼓励仅使用代码的答案,因为它们没有解释它是如何解决问题的。请编辑您的答案以解释此代码的作用以及它如何回答问题,以便它对 OP 以及其他有类似问题的用户有用。
【解决方案2】:

对我来说,答案是将我的承诺解析器从 .then 更改为 .spread。这与 Sequelize 返回数据的格式有关。

for( var i = 0; i < tags.length; i++ ){
    global.db.Tag.findOrCreate({
        name: tags[i]
    }).spread( function(tag, created){
        if( created ){
            global.db.PostTag.create({
                PostId: id,
                TagId: tag.id
            });
        }
    });
}

【讨论】:

  • 这是正确的。 .spread 是为遇到此问题的任何人处理 findOrCreate 的正确方法。 来自 sequelize 文档: “默认情况下,该函数将返回两个参数:一个结果数组和一个元数据对象,包含受影响的行数等。使用 .spread 访问结果." docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html
  • 使用也可以只使用await,它给你一个二元素数组,然后解构或抓取元素[0]
【解决方案3】:

global.db.Tag.findOrCreate({
    where:{
        name: tags[i]
    }, 
    defaults: {
    //properties you want on create
    }
}).then( function(tag){
    var created  = tag[1];
    tag = tag[0]; //new or found
    if( created ){

    }
}).fail(function(err) {

});
https://github.com/sequelize/sequelize/wiki/Upgrading-to-2.0

【讨论】:

    【解决方案4】:

    我遇到了同样的问题。从 1.7.0-alpha2 升级到 2.0.0-alpha2 解决了它。 干杯

    【讨论】:

      猜你喜欢
      • 2017-02-27
      • 2013-12-17
      • 2018-02-09
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多