[wix-data] Multiple References - another post :)

Hi,

The Data Types documentation for for wix-data states the following

  • Field Type - Reference/Multiple Items Reference

  • Data Type - JavaScript string/ JavaScript array of strings

  • Notes - An item ID or multiple items IDs from the referenced collection.

I expect to get an array of IDs when I use query() function for multiple reference field type as stated in the documentation b ut I am not getting it, is it how this API behaves or I have lost my mind?

Before writing this post, I have already read more than 10 posts about this topic and here is what I understand -

  • include() function doesn’t work with multiple reference field and totally ignores the field from the result but I don’t need the full objects, I only need the Array of IDs

  • queryReference() returns referenced objects - so you need to iterate over your whole collection to get references which sounds pretty expensive.

Thanks in advance for any help.

Cheers

HElloVarun Dev,

You will need something like this…

import wixData from 'wix-data';

// ...

wixData.query("myCollection")
  .eq("title", "Dr.")
  .find()
  .then( (results) => {
    if(results.items.length > 0) {
      let firstItem = results.items[0]; //see item below
    } else {
      // handle case where no matching items found
    }
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

You can find it here in the Corvid-API-Reference

Not to be confused, you can also cut this part here…

.catch((err)=>{let errorMsg = err;});

…off the code and later when you are done and all works perfektly, you can add it back.

So all you need is this pice of code…

import wixData from'wix-data';// ...  wixData.query("myCollection").eq("title","Dr.").find().then((results)=>{if(results.items.length >0){let firstItem = results.items[0];}})

Using include() method works only with single item reference field, you should use queryReferenced() .

Have a look at the Wix Data Multiple-References example (which is in the related posts box on this forum page).
https://www.wix.com/corvid/forum/tips-tutorials-examples/example-wix-data-multiple-references

I’m having the same issue.
I have 2 Collections: A, B.
B has a column called “As” (A-plural), which is a multi-reference field.
When querying records from B, I expected to get an object looks like:

{
  _id : "the-id",
  // ... some fields
  as: [ 
     "id1-from-collection-A",
     "id2-from-collection-A", 
     // etc.
  ]
}

but I don’t get the “as” field.
I guess it by design, but as in the original question of this post, the current solution is not trivial and might not be efficient as getting the “as” field as expected.
for now, my solution is to choose array type for the field and manually set the field for each record. It can’t scale, but for me it’s only a little inconvenience, as I have only a couple of records to maintain.

If someone has a better idea to overcome this it would be appreciated.