[SOLVED] Adding 1-to-1 relations

I’m trying to add a 1-to-1 relation with User <> Profiles (new class) in the database.

I have userId column in Profiles. This is only working when I set this column to a string and not a Relation.

Is this correct that a column to 1-to-1 relation should just be a string?

If not then how should I be setting the relation below?

const saveProfile: SubmitHandler<IFormInput> = async (data) => {

    if (!data) return;

    try {
    const currentUser = await Moralis.User.current();

    const User = Moralis.Object.extend('_User');
    const query = new Moralis.Query(User);
    const userDetails = await query.first();

    const Profiles = Moralis.Object.extend('Profiles');
    const getProfile = new Moralis.Query(Profiles);
    const profile = await getProfile.equalTo('userId', currentUser?.id).first();

    if (profile === undefined) {
      const newProfile = new Profiles();

      if (data.email) {
        userDetails?.set('email', data.email);
      }

      if (data.stableName) {
        newProfile.set('stableName', data.stableName);
      }

      if (data.userWebsite) {
        newProfile.set('userWebsite', data.userWebsite);
      }

      if (data.userInstagram) {
        newProfile.set('userInstagram', data.userInstagram);
      }

      if (data.userTwitter) {
        newProfile.set('userTwitter', data.userTwitter);
      }

      // Set 1-to-1 relation - sets current user ID as userID column in Profiles
      newProfile.set('userId', currentUser?.id);

      await newProfile.save();
      await userDetails?.save();

      refetchUserData();
      toastSuccess();
      }
   } catch (err) {
      console.error(err);
   }
}

You can use an objectId as a string. You can see the docs for an example. In that example, the parent column is set as a pointer. Just played around with it now but it may be better to do something like:

const Profile = Moralis.Object.extend('Profile');

// set profile data
const myProfile = new Profile();
myProfile.set('name', 'John Smith');

// save current user object in account column
myProfile.set('user', Moralis.User.current());
myProfile.save();
1 Like

Thanks for this. I guess maybe the docs weren’t as clear to me.

I was saving the userID by itself instead of the whole object.

You can certainly still use just the userID by itself but saving the whole object makes it a bit easier to get the “related” data (instead of making a separate explicit query to _User):

// look up profile
const query = new Moralis.Query('ProfileAnother');
query.equalTo('email', ''); 
const result = await query.first();

// fetch related _User
const user = result.get('user');
await user.fetch();

const address = user.get('ethAddress');