简体   繁体   English

使用流星插入设置唯一ID

[英]Setting unique id with Meteor insert

I'm linking the FB Graph API to Meteor so that I can retrieve a users photos and I'm having trouble setting the Meteor id to the Facebook id for each photo. 我将FB Graph API链接到Meteor,以便可以检索用户照片,并且在将每张照片的Meteor ID设置为Facebook ID时遇到麻烦。 Right now when the function is called it will return the same photo multiple times in the database since Meteor assigns a new _id to each photo each time. 现在,调用该函数时,由于Meteor每次都会为每张照片分配一个新的_id,因此它将在数据库中多次返回同一张照片。

For example, one entry might look like this: 例如,一个条目可能看起来像这样:

Object {_id: "cnMsxSkmMXTjnhwRX", id: "1015160259999999", from: Object, picture: "https://photoSmall.jpg", source: "https://photoBig.jpg"…}

And a second, after the call has been performed again, like this: 第二秒钟,再次执行调用后,如下所示:

Object {_id: "acMegKenftmnaefSf", id: "1015160259999999", from: Object, picture: "https://photoSmall.jpg", source: "https://photoBig.jpg"…}

Thereby creating two id fields in MongoDB. 从而在MongoDB中创建两个id字段。

The code I am using is below. 我正在使用的代码如下。 I've tried a number of things to fix the code to no avail. 我已经尝试了很多方法来修复该代码,但均无济于事。

Meteor.methods({
    getUserData: function() {
        var fb = new Facebook(Meteor.user().services.facebook.accessToken);
        var data = fb.getUserData();

        _.forEach(data.data, function(photo) {
            Photos.insert(photo, function(err) {
                    if(err) console.error(err); 
                });
            });
    }
});

Thanks in advance! 提前致谢!

Check if the photo exists prior to inserting it 插入照片之前检查照片是否存在

 ...

 _.forEach(data.data, function(photo) {
    if(Photos.findOne({id: photo.id})) return;

    ...

Another option is to add a unique key index to the id field. 另一种选择是向id字段添加唯一的键索引。 Or even use the _id field to store the id value. 甚至使用_id字段存储id值。 (be sure to use try catch to ensure it doesn't cause an error on the second insert). (请确保使用try catch来确保它不会在第二个插入中引起错误)。

Wouldn't there be something different to each of these with different ids? 每个ID都不同的东西会不会有所不同?

You could also clean up the uniques before you run them with _.uniq 您还可以在使用_.uniq运行唯一性之前清理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM