【发布时间】:2017-05-31 13:45:24
【问题描述】:
我在 Blaze 中使用 Meteor 框架。如何从 API 获取数据并且只在我的 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 }); }); },
当使用带有“upsert: true”的“myCollection.update”时,它显然不会插入新条目。检查 API 中的数据并仅插入不重复的新条目并更新现有条目的最佳做法是什么?
谢谢。
【问题讨论】:
-
如果您需要保证唯一性,您还应该在数据库中放置适当的唯一索引,如果没有它们,您在流星中所做的任何事情都可能会失败。
-
为什么不直接用Collection.upsert() 来做呢?
标签: javascript mongodb meteor meteor-blaze