How to clone/copy instance item/row in sequelize
Asked Answered
O

4

12

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.

Obrian answered 7/8, 2018 at 11:18 Comment(1)
can you not just find the row delete the id (which I assume is PK and A_I) and create the data?Celia
L
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
    })
    
Lipps answered 7/8, 2018 at 12:10 Comment(0)
C
6

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.

Commons answered 12/10, 2021 at 10:57 Comment(0)
C
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);
Crescent answered 28/9, 2020 at 9:50 Comment(0)
S
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.

Solipsism answered 7/8, 2018 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.