lodash-id icon indicating copy to clipboard operation
lodash-id copied to clipboard

How best to merge list of new/updated objects into existing list

Open jfsiii opened this issue 8 years ago • 1 comments

I receive an array of objects from an API and would like to store them. Sometimes the objects match those already in the db and other times they've been altered. This sounds like a great use of upsert.

Unfortunately, the only way I can get this to work is

users.forEach(user => db.get('users').upsert(user).write())

where users is the array of objects. Is there a better way to do this than calling write in a loop?

jfsiii avatar Jun 20 '17 04:06 jfsiii

Hi @jfsiii,

Yes, you can do:

users.forEach(user => {
  // will change only in memory
  db.get('users').upsert(user).value()

  // you can also use `commit` if you don't need a returning value
  // db.get('users').upsert(user).commit()
})

// then write to file
db.write()

typicode avatar Jun 20 '17 08:06 typicode