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.