[SOLVED] How to get _id of a recently inserted record so you can use it as your Primary Field.

My main purpose of this is to basically copy the _id of the recently added record and paste it in the “clientId” field which will serve as the primary field of the same record—if that makes sense. This all happens after the user hits the “Submit” button.

Here’s what I tried:

export function submitBtn_click(event) {
    $w('#dataset1').setFieldValue('createdBy', $w('#currentUserField').value)
    $w('#dataset1').onAfterSave((AfterSaveHandler) => {
      console.log("This is the ID of the new record: "+ AfterSaveHandler._id)

      let clientID = AfterSaveHandler._id
      $w('#currentUserIDField').value = clientID
      console.log("Successfully copied ID: "+ clientID)

       $w('#dataset1').setFieldValue('clientId', $w('#currentUserIDField').value)
       console.log("Successfully Pasted ID for reference!!")
       })
    
}

The code executes with no errors but when I check the collection, the “clientId” field is empty. If there’s another way of doing this, please let me know.


EDIT
I finally solved it!
It took me a while but it’s working now!

I disconnected the Submit from the dataset but all of the input fields that need to be submitted are still connected to their corresponding fields via dataset.

Here’s the code:

//DON'T CONNECT SUBMIT BUTTON TO DATASET
export function submitBtn_click(event) {
    //Get the _id of the most recent record that has been added.
    $w('#dataset1').onAfterSave((AfterSaveHandler) => {
    wixData.get("collectionName", AfterSaveHandler._id)
          .then((item) => {
            item.fieldname = AfterSaveHandler._id; //Pastes _id to your     desired field
                        wixData.update("collectionName", item);                
                    })
                    .catch((err) => {
                        let errorMsg = err;
                    });
    })
   $w('#dataset1').save()
}

Why not to update both fields together?

Can you elaborate on that? I’m quite new to this. From what I know, the _id is only generated once a record has been created. That’s why I used AfterSaveHandler . _id to get the _id and then hopefully insert it in clientId field of the same record.


EDIT
I tried the toUpdate method and it does successfully copy the _id to the clientId field however, the rest of the fields become empty since it requires all of the fields to be updated as well.

I also tried the toSave method and it does the same thing, it clears the rest of the fields.

export function submitBtn_click(event) {
    $w('#dataset1').setFieldValue('createdBy', $w('#currentUserField').value)
    $w('#dataset1').onAfterSave((AfterSaveHandler) => {
      console.log("This is the ID of the new record: "+ AfterSaveHandler._id)

      let clientID = AfterSaveHandler._id
      //SAVE
      let toSave = {
         "_id":        clientID,
         "clientId":   clientID
      };

      wixData.save("test", toSave)
      .then( (results) => {
            let item = results; 
         } )
         .catch( (err) => {
            let errorMsg = err;
         } );
      })
    

@chocookie22 There’re several way to achieve that… But in your original code you forgot to save the client id after you set it.
See:
https://www.wix.com/velo/reference/wix-dataset/dataset/save

@jonatandor35 Would you be so kind enough to tell me what’s the most straightforward way of doing it? I just want the _id to be pasted on clientId field of the same record so I can use it as the primary field.

@chocookie22
All the ways are fine and it really depends on the specific use case. but especially if you want to use insert it on different ages using different functions, I’d create an afterInsert Data Hook :

Like this:

//backend/data.js
import wixData from 'wix-data';
export function myCollection_afterInsert(item, context) {
  item.clientId = item._id;
return wixData.update(context.collectionName, item, {suppressHook:true, suppressAuth: true}).then(() => item);
}

Alternatively I’d create my own record ID and then insert all at once:

//declare a createId() function to create a random uuid, you can can install the uuid npm for that
const item = {_id: createId()};
item.clientId = item._id;
wixData.insert('collectionName' itme);

or use a beforeInsertHook:

//backend/data.js

//declare a createId() function to create a random uuid, you can can install the uuid npm for that
import wixData from 'wix-data';
export function myCollection_beforeInsert(item, context) {
  item._id = createId();
  item.clientId = item._id;
return item;
}

And of course you can go with the code you posted (just add dataset.save(); no need to push this value to any UI element).
As I said, the best choice depends on the specific use case.
See more:

@jonatandor35 Thank you so much for your input! I highly appreciate it.

I never thought it would get this complicated. So I will try to stick with the original code for now. I added $w ( ‘#dataset1’ ). save () to the original code but I get this message in the console logs:

save operation failed: DatasetError: Operation (save) not allowed during save

It does add a record with the stuff I inputted in the form but the _id has not been copied to the clientId field.

@jonatandor35 I finally did it! I updated my post and included the working code. Thanks!