0

I have a database which is being populated from different API's.

Right now I am just removing all content from the database and populating with all the data.

However, this is not a good approach since I want to keep the original documents.

What is best way to check if an object exists; if it does, it should be updated with the new data, and if it doesn't, it should just be created. So I am trying to create a updateOrCreate function.

I have read a little about upsert, which seems to do this. However, wouldn't it just be as efficient to create a loop:

itemsToBePopulatedWith.forEach(item => {
  Item.findOne({ name: item.name }).then(existingItem => {
    if (existingItem) {
      existingItem.date = item.date;
      existingItem.user = item.user;
      ...

      existingItem.save();
    } else {
      Item.create({ date: item.date, user: item.user });
    ]
  });
});

I need to do some additional checks, so it would be great if I could just do a simple search to decide whether to update or insert. But it might be too inefficient.

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • The different with `"upsert"` is that you contact the database **once** as opposed to "twice". Also unless you actually need the document back, even `.findOneAndUpdate()` is not needed and you should use `.update()` instead. Or if you actually are doing "bulk" then `.bulkWrite()`. But **always** `"upsert"` or *"insert and reject duplicate errors"*. Nothing alike to `.find() -> "modify" .save()` which is an anit-pattern best avoided. – Neil Lunn Jul 26 '17 at 21:55
  • Also in case it's not entirely obvious this linked duplicate is an example of where the "accepted" answer is completely incorrect. The better answers and patterns are indeed the higher voted responses. – Neil Lunn Jul 26 '17 at 21:56

0 Answers0