Skip to content

Problem with insertAndFetch() inside upsert() #627

@lehni

Description

@lehni

Test case

https://runkit.com/lehni/objection-has-one-relation-with-upsert

Description

I'm experiencing something strange with my upsert() method here. When I run it on an empty has-one relation through model.$relatedQuery('relation').upsert(…), I get the error "Cannot read property '$id' of null", from InsertAndFetchOperation.js:26.

But when I replace the call of upsert() with a direct call of insertAndFetch() (which is used internally in upsert() also, since results === 0), this works.

I've started debugging, and found that while in the direct call, InsertAndFetchOperation.onAfter2(builder, inserted) receives an array with one element in inserted, but when I use the approach of upsert() above, then inserted is just the inserted model, not wrapped in an array. super.onAfter2(builder, inserted) then wrongly thinks it's an array and tries to unwrap it (inserted[0]), resulting in this error. I don't understand why this is happening.

there is already a check for arrays here, but the problem happens before.
If I add the same check before this line then it starts working as expected:

onAfter2(builder, inserted) {
  const modelClass = builder.modelClass();
  const insertedArray = Array.isArray(inserted) ? inserted : [inserted];
  const maybePromise = super.onAfter2(builder, insertedArray);

This change solves the issue and doesn't break any existing tests, but I cannot tell if this is right or not : )

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