Insert multiple items (with the same object)

Hello,

This is a tip I would like to share (not a question).

The problem:

Let’s say you need to insert 3 items with the same field data all at once. You created an object with all the field data you need for that item. You use a For loop and try to insert the object 3 times. Keep in mind the following:

– After each insert, the wixData.insert(‘collection’, yourObject) functiion will mutate yourObject.
– That’s right, the insert function will assign yourObject._id to yourObject if yourObject._id doesn’t exist.
– Your For loop will break after the first iteration since the insert function will throw an error saying that ‘the itemId already exists’.
– That’s because after the first iteration the insert function assigned yourObject._id to yourObject, the loop does the second iteration the insert function will use the same yourObject._id as the item id to insert. And it will find that the item with the same id already exists.

The solution:

Do the following:

const yourObject = {
someProperty: value
}

for (let i= start; i <= end; i++){
await wixData.insert(‘collection’, yourObject)
delete yourObject._id
}
And of course since you need to ‘await’, make sure you are using an async function.

Problem solved!! Simple :slight_smile:

This is not written in the Wix reference but I thought I share this so that you don’t have to waste half an hour like I did to figure out why.

Happy coding.

1 Like