top of page
Search

How to update specific fields

  • Writer: J. D.
    J. D.
  • Sep 22, 2019
  • 1 min read

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.

 
 
 

1 Comment


Jess
Jun 06, 2022

Hi JD! This is amazing. Thanks for posting. Quick question though. I keep getting an error regarding the collection name in the beforeUpdate hook (error: WDE0001: Collection name must be a string ). I have updated all of the collection names as needed in that portion of code (see blue bold areas below), but for the life of me I can't figure out where to put the collection name as a string. I'm pretty sure I can't include a string following the context .dot operator but that's where there error keeps popping up. Any suggestions? Your post is already a HUGE help, and any further suggestions would be greatly appreciated :)


// the code I updated in data.js per your…


Like

FOOTER

bottom of page