I’m having trouble with
Code to change the “Status” field in my CMS dataset from Published to Draft.
Working in
Dev mode
Site link
See screenshot below.
What I’m trying to do
Set the Status record flag from Published to Draft 14 days after the Created Date and the Perpetual value is false. I’m trying to unpublished old records in the dataset as a way to retain the data but not have them appear on my site. Some of the records stay published by excluding them with the Perpetual boolean field.
This code is currently connected to a button but I will move it to an automations schedule or the “back end” once I figure out how to accomplish that.
What I’ve tried so far
This code was generated with velo AI and is crashes saying the classifieds collection does not exist.
import wixData from 'wix-data';
const COLLECTION_NAME = 'Classifieds';
const PAGE_SIZE = 1000;
const AGE_IN_DAYS = 14;
$w.onReady(async function () {
try {
const updatedCount = await updateExpiredClassifieds();
console.log(`Updated ${updatedCount} classified record(s) to draft.`);
} catch (error) {
console.error('Failed to update expired classifieds:', error);
}
});
async function updateExpiredClassifieds() {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - AGE_IN_DAYS);
let queryResult = await wixData.query(COLLECTION_NAME)
.lt('_createdDate', cutoffDate)
.eq('perpetual', false)
.limit(PAGE_SIZE)
.find();
let updatedCount = 0;
while (queryResult.items.length > 0) {
for (const item of queryResult.items) {
if (item.status !== 'draft') {
await wixData.update(COLLECTION_NAME, {
...item,
status: 'draft'
});
updatedCount += 1;
}
}
if (!queryResult.hasNext()) {
break;
}
queryResult = await queryResult.next();
}
return updatedCount;
}```
**Extra context**
Anything else that might help - edge cases, screenshots, etc.
Screenshot of the CMS dataset named Classifieds showing the Status system field and the Perpetual boolean field.
