Is there a shorthand way of updating a relationship/array field with an `update` call?

default discord avatar
tinouti
5 months ago
3

Assuming the following

messages

field in my

threads

collection:


{
    name: 'messages',
    type: 'relationship',
    relationTo: 'messages',
    hasMany: true,
    required: true,
    min: 1,
},


Is there a shorthand and/or better way of doing this?



const thread = await payload.findByID({
  collection: 'threads',
  id: message.thread.id,
  depth: 0,
});
const update = await payload.update({
  collection: 'threads',
  id: message.thread.id,
  data: {
    messages: [ ...thread.messages, message.id ],
  }
});


And similarly for removing an item, or is fetching the doc first to get the field value and do the addition/removal myself the only way?

  • discord user avatar
    jarrod_not_jared
    Payload Team
    5 months ago

    That’s currently the only way to do it. Get the full array, mutate it, then update doc

  • default discord avatar
    tinouti
    5 months ago

    Gotcha, wanted to make sure I wasn't missing a hidden method to update it directly. Thanks Jarrod! 🙏

  • default discord avatar
    superwafflepuffs
    4 weeks ago

    Any possibility of us getting access to something that scales better? I'm trying to use this for a memberships section.

    Organizations { members: Relationship<Users> }

    and in order to make access handling easier I also want to store an array of memberships on the user object

    Users { memberships: Relationship<Organizations> }

    Would be great if we could get access to all the power of mongo $push, $pull, etc...

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.