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.
There is no such direct function for that , What you can do is :
- Fetch the object that you want to clone/copy
- Remove Primary Key from it
Make a new entry from it
model.findOne({ //<---------- 1 where : { id : 1 } , raw : true }) .then(data => { delete data.id; //<---------- 2 model.create(data); //<---------- 3 })
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.
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);
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.
© 2022 - 2024 — McMap. All rights reserved.
find
the row delete theid
(which I assume is PK and A_I) andcreate
the data? – Celia