我应该如何在Meteor Mongodb中插入一堆数据?

时间:2013-01-22 02:37:01

标签: mongodb meteor

需要花费很长时间才能在MongoDB中保存500多名Facebook好友,我认为我做错了。我将粘贴我正在插入的内容:

models.js:

Friends = new Meteor.Collection('friends');
Friend = {
set : function(owner, friend) {
    var user_id = get_user_by_uid(friend['uid']);
    return Friends.update({uid: friend['uid'], owner: owner}, {$set:{
        name : friend['name'],
        pic_square : 'https://graph.facebook.com/'+friend['uid']+'/picture?width=150&height=150',
        pic_cover : friend['pic_cover'],
        uid : friend['uid'],
        likes_count : friend['likes_count'],
        friend_count : friend['friend_count'],
        wall_count : friend['wall_count'],
        age : get_age(friend['birthday_date']),
        mutual_friend_count : friend['mutual_friend_count'],
        owner : owner,
        user_id : user_id ? user_id['_id'] : undefined
    }}, {upsert: true});
}
}

server.js:

// First get facebook list of friends   
friends = friends['data']['data'];

_.each(friends, function(friend){
    Friend.set(user_id, friend);
});

2+用户的负载很高,插入数据库需要很长时间。我应该在这里改变什么?

1 个答案:

答案 0 :(得分:4)

表现糟糕,我认为有两个原因。

首先,您在客户端上遇到minimongo性能,而不是mongodb性能。 minimongo无法编制索引,因此upsert代价昂贵 - 数据库大小为O(n^2)。只需在数据库更新之前将if (Meteor.isSimulation) return;语句添加到模型中。

查看一些示例代码,了解如何组织代码,因为Friend.set(user_id, friend)应该在方法调用中发生,通常在model.js中定义。然后,如果它被检测为模拟调用的客户端,它应该转义,而不是服务器执行它。

其次,您正在使用uidowner之类的密钥,而不是将其作为密钥。在服务器启动代码中,添加Friends._ensureIndex({uid:1, owner:1})

如果这些都不起作用,那么您对Facebook的查询可能会在某种程度上受到速率限制。

如果您的费率有限,请查看https://stackoverflow.com/a/8805436/1757994,了解您收到的错误消息。

他们几乎肯定不希望你以你的方式复制图形。您可能想要考虑不复制图形而只是在使用基础上获取数据,因为它无论如何都会很快变得陈旧。