$push to array

default discord avatar
9 months ago

Is there a way to $push an entry to an array with the API or do I need the replace the array with a new one that has the new value included?

  • discord user avatar
    Payload Team
    8 months ago

    Can you give some context here? I think it's the latter but would like to understand how you're trying to achieve this to make sure

  • default discord avatar
    8 months ago

    I'm following up on this for @Daddaaff since I encountered that yesterday;

    I have a series of forms (with questions) where users facing the front-end progressively update entries (through a graphql mutation atm). I'm using arrays to structure the questions on the back-end because I want my own client to be able to add as many questions as they want inside a repeater without me having to version control new questions every time

    At the moment I need to take the entire payload and add a new object to the array (or update the entry inside the array if it's an entry already existing, ie. an update to a previous question instead of an answer to a new question) whenever I do a graphql mutation on the FE

  • default discord avatar
    8 months ago

    yes, appending to array using payload API is a pain. I think using Mongoose model and using $push operation directly might be the way to go here. Not sure, it makes sense to add every MongoDB operation to Payload API.

  • default discord avatar
    8 months ago

    @akshay if you want versioning it's the only option. And it's not like $push is so exotic

  • default discord avatar
    Above The Clouds
    3 months ago

    I have reached the same limitation - using the local API, how can we push references to previously created documents in an array of relationship?

    PS: I have it working using mongoose, it seems a common use case for the local API though - how to save arrays of relationship if you don't have the push?

  • default discord avatar
    3 months ago

    You need to have the existing values and then merge in your new values before updating - or use the Model like others have said. When using a Model, just know that hooks and access control do not execute when using the underlying Model

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


Connect with the Payload Community on Discord



Can't find what you're looking for?

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