Skip to content

Add support for an upsert creation on a non-id field #4

Open

Description

Currently, create uses the MongoDB save method, which upserts on _id. Since we generate IDs, that's a problem if another field is uniquely indexed and conflicts.

Correct behavior is up to the user application. Do they want to retrieve instead of inserting? Or just show an error? Who knows.

However, if they really want their object to override anything in the database, we should make it easer than trying to create, failing, retrieving the conflicting object's ID somehow, then forcing an update. Or just forcing an update on the constraint field. That's either two or three database hits, depending how it's done.

If overwriting is the preferred behavior, then instead it would make sense to do a findAndModify on a constraint field with the upsert option set. That takes only a single database command rather than two or three (try to insert/force update).

It might look like this:

$coll->upsert_on( 'name' => { %constructor_attributes } );

That would create a constraint based on the 'name' attribute of the object, then drop the ID from the packed object and do findAndModify with the constraint and upsert true. The object returned would then be thawed into the object just like we do with create.

Activity

  1. toddbruner commented on Feb 10, 2016

    @toddbruner
    Contributor

    +1 for this idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions