question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Create or update record (batch)

See original GitHub issue

Hey, guys.

What is the proper way of create or updating records in one statement? I fetch the updated data and I need to save into the database. I understand all validation must be made on javascript and that makes us to do try/catch everywhere.

await database.action(async () => {
  const postsCollection = database.collections.get('posts')
  try {
    // try to find post by id
    const post = await postsCollection.find('abcdef')
    // if it exists, update it
    await somePost.update(post => {
      post.title = 'Updated title'
    })
  } catch (error) {
    // if post was not found, create it
    const newPost = await postsCollection.create(post => {
      post.title = 'New post'
      post.body = 'Lorem ipsum...'
    })
  }
})

A bit verbose, but it works. This is for one record, but the server returns 20 records, so it’s not optimal. We need batch then.

let statements = [
  database.action(async () => {
    const postsCollection = database.collections.get('posts')
    try {
      // try to find post by id
      const post = await postsCollection.find('abcdef')
      // if it exists, update it
      somePost.prepareUpdate(post => {
        post.title = 'Updated title'
      })
    } catch (error) {
      // if post was not found, create it
      const newPost = postsCollection.prepareCreate(post => {
        post.title = 'New post'
        post.body = 'Lorem ipsum...'
      })
    }
  })
]
database.batch(statements);

The code above raises an error. I’m not sure why 🤔

Note: In Realm, this can be achieved this way:

realm.write(() => {
  // just pass `true` as third argument
  realm.create('Post', {id: 1, title: 'New post', body: 'Lorem ispum'}, true);
});

https://realm.io/docs/javascript/latest/#creating-and-updating-objects-with-primary-keys

cc @radex

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:18 (8 by maintainers)

github_iconTop GitHub Comments

13reactions
radexcommented, Feb 25, 2019

This:

const actions = [
  database.action(async () => {
     // ...
  })
]
await Promise.all(actions);
await database.batch(...operations);

is misguided. batch must be called within an Action — but you don’t have to do one Action per operation — doesn’t really make sense. An Action ought to encompass all related operations, and your finds, created, and updates are related.

Here’s how you create or update multiple records in one go efficiently (yes, it’s not the prettiest code and could be a bit easier, but should work unless I misunderstand your problem):

database.action(async () => {
  // check which posts already exist
  const existingPosts = await database.collections.get('posts').query(Q.where('id', Q.oneOf(['abcdef', 'dasdasd', 'asdasd'])))

  const postsToCreate = IDs that are not contained in existingPosts
  const poststoUpdate = Posts that are contained in existing Posts

 await database.batch(
   ...postsToUpdate.map(post => post.prepareUpdate(() => {
     post.title = 'Updated title'
   })),
   ... postsToCreate.map(postData => collection.prepareCreate(post => {
    post.title = 'New title'
  }))
 )
})

Does this make sense to you?

2reactions
Acetyldcommented, Oct 12, 2021

Is there any update on this?. A upsert/ merge function?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Create or update bulk records in Power Apps - Microsoft Learn
Updating or creating records in bulk allows you to act on many records at once. Here are some scenarios where you would want...
Read more >
Update the records by using batch apex - Salesforce Developers
Hi all, By using batch apex, write an apex class to update the records of custom sobject as like gender is male then...
Read more >
Mass Update Records Through Batch Processing
It is possible to do a mass update for multiple records at once by customizing a screen to do the batch processing for...
Read more >
Using batch update operations | Tray.io Documentation
This uses the Batch update records operation. Set the value of Record type to the type of object we are updating, 'Account' in...
Read more >
Create, Delete, or Update Tens of Thousands of records at a ...
Using this new invocable you will be able to transact records with little concern for limits – so long as you set your...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found