Find or create with SequelizeJS

22,722

Solution 1

I had the same problem. Upgrading from 1.7.0-alpha2 to 2.0.0-alpha2 solved it. Cheers

Solution 2

For me the answer was changing my promise resolver from .then to a .spread. This has something to do with the format that Sequelize returns data.

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

Solution 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
Share:
22,722
tonymx227
Author by

tonymx227

Updated on September 07, 2021

Comments

  • tonymx227
    tonymx227 over 2 years

    I try to use the "findOrCreate" function of SequelizeJS but it doesn't work.

    The variable "created" is "undefined", so I don't know why because it's a variable used by 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
                });
            }
        });
    }