我在Blaze使用Meteor框架。我如何從API獲取數據並只在MongoDB集合中插入新數據而不重複?如何更新沒有重複的MongoDB
從API獲取數據。
if (Meteor.isServer) { Meteor.methods({ fetchApiData: function() { this.unblock(); return Meteor.http.call('GET','http://jsonplaceholder.typicode.com/posts');},
將數據插入數據庫:
populateDatabaseApi: function() { Meteor.call('fetchApiData', function(error, result) { myCollection.insert({ //upsert: true, A: result.data.title, B: result.data.userId, C: result.data.id }); }); },
當使用 「myCollection.update」 與 「UPSERT:真正的」 它並不明顯插入新的條目。什麼是最好的做法來檢查API的數據和只插入新的條目沒有重複和更新現有的條目?
謝謝。
如果你需要保證唯一性,你應該在數據庫中放置適當的唯一索引,如果沒有它們,你在流星中做的任何事情都可能失敗。 – Paul
爲什麼不用[Collection.upsert()](https://docs.meteor.com/api/collections.html#Mongo-Collection-upsert)這個簡單的方法來做到這一點? –