Search code examples
referencebackendrepeatermembervelo

How to fill a reference field automatically in Wix (Velo), with or without code?


I am using a reference field, which contains users nickname, to make a connection between my main collection and 'public data' collection created as default by Wix. I created this reference field to populate a repeater from the two 'main' and 'public data' collections. Is it possible to automatically fill a reference field without using code? If not, then how can use 'beforeInsert' hook to fill the 'the reference' field using code. I tried to do so in the backend by this code, but it doesn't work.

import { currentMember } from 'wix-members-backend';

export function Collection1_beforeInsert(item, context) {
currentMember.getMember()
        .then((member) => {
            const id = member._id;
            const fullName = `${member.contactDetails.firstName} ${member.contactDetails.lastName}`;
            const nickname = member.profile.nickname
            console.log(nickname)
            item.referenceField= "nickname"
            // return member;
        })
        .catch((error) => {
            console.error(error);
        });
return item;
}


Solution

  • First off, I'm assuming you're using a regular reference field and not a multi reference field.

    Second, it's important to understand how reference fields work before continuing. The reference field holds the ID of the item it is referencing. So when you say the reference field contains a user's nickname, that can't be true. It can contain the ID of the item in PrivateMembersData collection with the nickname you want.

    Third, as just mentioned, the nickname field does not exist in the PublicData collection. It is part of the PrivateMembersData collection.

    So, if you want to connect your collection to another with the nickname field, you need to set your reference field to reference the PrivateMembersData collection and then store the proper ID in that field.

    (Side point: In your code you are putting the same string, "nickname", in every reference field value. You probably meant to use nickname without the quotes. You're also not using promises correctly.)

    You can try this code. It should get you closer to what you're looking for.

    import { currentMember } from 'wix-members-backend';
    
    export async function Collection1_beforeInsert(item, context) {
        const member = await currentMember.getMember();
        item.referenceField = member._id;
        return item;
    }