Hey there!
I just got a database from a client with hundreds of fields and now they want me to make the data collection schema more robust with reference fields instead of everything stored in text.
In the Data Collection called “People” they have fields for “CountryName”, “StateName” and “CityName”. So instead of manually editing over 2 500 records in the People Data Collection I though I would make a smart function that connects the reference fields automatically.
So I call the function by executing:
searchAndUpdatereferenceFieldForce("People", "state", "stateName", "States");
And then I made the below function and it searches, finds and connects values as it should but if the state is not present in the States Data Collection I create a new one and connect the record to the newly created. But for some reason the execution goes so fast so the function won’t find the newly inserted one and keeps in creating new ones in the States Data Collection so I end up having like 400 New York records instead of one.
How can I hold and wait without slowing things down…?
export function searchAndUpdatereferenceFieldForce(collectionName, fieldToUpdate, fieldToSearch, refCollectionName) {
return wixData.query(collectionName)
.isNotEmpty(fieldToSearch)
.limit(1000)
.find()
.then((results) => {
if (results.totalCount > 0) {
let items = results.items;
console.log("Items to update:" + results.totalCount);
items.forEach((item) => {
let searchValue = item[fieldToSearch];
return wixData.query(refCollectionName)
.eq("title", searchValue)
.ascending("title")
.limit(1)
.find()
.then((refresults) => {
console.log("Records found:" + refresults.totalCount);
if (refresults.totalCount > 0) {
item[fieldToUpdate] = refresults.items[0]._id;
return wixData.update(collectionName, item).then((updatedItem) => {
console.log(JSON.stringify(updatedItem));
})
}
let newItem = {
title: item[fieldToSearch]
}
return wixData.insert(refCollectionName, newItem).then((inserted) => {
item[fieldToUpdate] = inserted._id;
return wixData.update(collectionName, item).then((updatedItem) => {
console.log(JSON.stringify(updatedItem));
})
})
})
})
}
})
}
Please help me!
#datacollection #referencefield #backend #wixData #update #insert