How to insert Reference by using Wix Code?

Hi everyone,
Let me start off by saying that Im thoroughly confused.
So I’ve 2 collections - CCDB & IDB
CCDB has the primary key of Champion ID (field key:champId, type:text)
IDB has a primary key DeviceName (field:title, type:text) and a reference field Champion ID (field key: champId, type: reference).
So, n items in the IDB collection belong to 1 item in CCDB collection.

Now, when I’m inserting data into IDB collection using following code below, the database shows a red underline saying : “Cell value type is Number. Change to Reference.”

getitems("pc").then(res => {
let toInsert = {
 "title":  res[i].champion_id, //reference to CCDB
 "description": res[i].Description, 
 "deviceName": res[i].DeviceName,
 "itemId": res[i].ItemId 
} 
wixData.insert("IDB", toInsert)
  .then(results => {
    let item = results;
    console.log(item);
 })
.catch(err => {
 let errorMsg = err;
 console.log(errorMsg);
  });
})


I searched the documentation and found wixData.insertReference()… but im not sure how to use the method in this scenario or even if it is possible to use.
And since the number of Items in IDB would be more than 100, I cant insert reference manually. How can I solve this with code?
Thanks.

Hey
You should not add a number field with the champId stored as a reference when there is reference fields to use. Go to your data collection and change the field type to Reference and choose the other data collection and you will have a real reference setup. If you need to use 1-to-many you select Allow Multiple Items otherwise just leave this disabled. Then you can insert and update the refererences just using the primary records _id and make sure when insert or update you just set the champId = primaryRecord._id or what the key is that you use.

If you need more help reply here

Thanks for the reply,
So, is the error just showing because the reference field is of type number.
I tried to change → “title”: (res[i].champion_id).toString()
but after the operation, the database just shows “reference is broken” error.
That again confused me.
Thanks again. :slight_smile: