简体   繁体   中英

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. 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.

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.

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. Or even use the _id field to store the id value. (be sure to use try catch to ensure it doesn't cause an error on the second insert).

Wouldn't there be something different to each of these with different ids?

You could also clean up the uniques before you run them with _.uniq

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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