So been reading a lot and working a code that does not work.
Before you pointing me more reading here are 2 articles that I read twice:
My objective: Insert a record into a collection and immediately get the "_id", to use it as value of the insert into another collection.
What I'm doing wrong?
Here is the code that is inside an "Add new guest" button
// Functions that insert the data. async function dataGuestUpdater(myData) { const results = await wixData.insert("EventsGuest", myData); let mypromise = fnDoze(500); -- timer for 500 ms return results.items[0]; }
var toInsert = { "eventid": $w('#txteventID').value , "guestname" : $w('#txtGuestUser').value , }; let iParticipant =""; dataGuestUpdater(toInsert) .then(res => { setTimeout(() => { //another timer $w("#txtmessage").text = "Guest Added!" ; $w("#txtmessage").show(); $w('#dataset2').refresh(); }, 1000 ) console.log(res.toString()); iParticipant = res._id; // Here is the value trying to get.
}
);
// Blank value console.log("Participant: " + iParticipant);
var toInsert={ "eventid":$w('#txteventID').value, "guestname" :$w('#txtGuestUser').value, }; wixData.insert("EventsGuest",toInsert) .then(result => { // <= Here you are consuming the promise. console.log(result) // result.items["_id"] is the id from Collection inserted row. })
.catch(err => {console.log("Insert Error:", err)} The "wixdata.insert" is a promise that returns the inserted items. Use .catch() o get the promise error.