11

I tried to find a way to copy/clone instances in Sequelize but without success. Is there any way to do it with a built-in function or without? What I want is to simply copy rows in the database and the new item should have only a different id.

Muhammad Tahir
  • 77
  • 1
  • 10
agims7
  • 216
  • 2
  • 6
  • 16

4 Answers4

20

There is no such direct function for that , What you can do is :

  1. Fetch the object that you want to clone/copy
  2. Remove Primary Key from it
  3. Make a new entry from it

    model.findOne({ //<---------- 1
                    where : { id : 1 } , 
                    raw : true })
    .then(data => {
        delete data.id; //<---------- 2
        model.create(data); //<---------- 3
    })
    
nwxdev
  • 4,194
  • 3
  • 16
  • 22
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
5

As said, there is no such direct function for that (thanks Vivek)

If you find it useful, place the following code on your model class:

async clone() {
    let cData = await THISISMYMODEL.findOne({
        where: { id: this.id},
        raw: true,
    });

    delete cData.id;
    return await THISISMYMODEL.create(cData);
}

Take into account that "THISISMYMODEL" should be the model class defined and "id" the primary key attribute used.

Also take into account the use of Foreign Keys (relations with other models), it will use the same keys. Otherwise you should clone those instances too.

acolchagoff
  • 1,926
  • 3
  • 18
  • 30
Adrian Sanchez
  • 121
  • 1
  • 4
3

You may need to update the name though or some other field to identify it as a copy,

const data = await model.findOne({ where: {id: 1}, raw:  true, attributes: { exclude: ['id'] } });

data.name = data.name + '(copy)';
const newRecord = await model.create(data);
adnan shuja
  • 183
  • 1
  • 2
  • 7
0

Write a Model.create(data) function inside Model.js and call this function from inside of a loop, as many times you need it will create the copy of the same data.

thirtharaj
  • 11
  • 4