top of page
Search
  • Writer's pictureJ. D.

How to update specific fields

Updated: Jan 7, 2020

Someone has asked about it lately, so I'm posting it here. (I know it's quite trivial but I hope someone will find it helpful.). So, sometimes you want to update some specific fields while you don't have the full object in the front end and you don't want to write a new query to pull it from the database. Here is an easy solution:

FRONT END: Put only the values you wish to update in the object:

let toUpdate = {
  _id: "sdfedas_dwefedsa_da34dfesad",
  status: "unavailable",
  soldout: true,
  fieldsToDelete: ["discount", "promotion"]
}
wixData.update("CollectionName", toUpdate);

The keys in red are mandatory. If you don't have the fieldsToDelete key, it'll run a regular update and won't update the specific fields only. So If you don't want to delete any field, just put "N/A" there:

let toUpdate = { 
  _id: "sdsadas_dwasdsa_dawsdfesad",
  status: "unavailable",
  soldout: true,
  fieldsToDelete: ["N/A"] 
};

BACKEND

In the backend/data.js, use this code:

function updateFields(item, collection) {
 let fieldsToUpdate = Object.keys(item).filter(e => e !== "fieldsToDelete");
 return wixData.get(collection, item._id, { "suppressHooks": true })
  .then((objToUpdate) => {
    fieldsToUpdate.forEach(e => objToUpdate[e] = item[e]);
    item.fieldsToDelete.forEach(e => delete objToUpdate[e]);
    return objToUpdate;
   })
}//no need to modify or update anything in the above function

//beforeUpdate hook:
export async function CollectionName_beforeUpdate(item, context) {//use the relevant collection name here
 if (item.fieldsToDelete) {item = await updateFields(item, context.collectionName); }
return item;
}

And that's all, it'll work for a single update as well as for bulkUpdate and no need to make an effort to retrieve the full items whenever you wish to update them.

443 views1 comment
bottom of page