Update the most recent record in a collection

I know how to update a record from here
https://www.wix.com/velo/reference/wix-data/update

The question is how do I find the most recent record in a collection and update a field there?

Thank you in advance

Do a query on the collection. If you do not specify any params, wix-data sorts on _createdDate , descending, meaning you sort the collection on date created with the most reent one on top. Then just return 1 row (limit=1). That should do it.

2 Likes

Thank you so much! That worked!
Just one more thing. Do you know how do I retrieve the _id from the query so that I can use it later.

when loading in the data you should use

    .descending( "_updatedDate" ) 

I used it in one of my functions with “_createdDate”


 return wixData.query("OffertesTestRef")
        .descending("_createdDate")
        .find()
        .then((res) => {
 //console.log("firstload reached")
             return res
        })

I needed the items to use somewher else, but you should filter it .

something like:

$w("#myDataset").setFilter( wixData.filter()
.decending("_updatedDate")
);

Kind regards,
kristof.

1 Like

Same way as any other field in the returned resultset. Lets assume the var you used to pipe the result to (eithet bu .then or await) is called “result”, This var now holds, after the query result is returned, an array of objects, better yet, an array of only 1 object, if you used “limit+1”. So the full path would be:
let theIdFromTheRowWeWant = result.items{0}._id;

meaning:
results=the var you asigned to catch the result
items = the hard coded array name (by wix) inside the retuned object holding all rows returned
[0]=first row inside the array (arrays are zero-based in JS, so 1=0, 2=1, etc)
_id = … the _id