Meteor collection find() method is undefined even though its subscribed

349 views Asked by At

I'm trying to implement a photo viewer app that stores image url and it's belonging user id in a collection. When I try to Collection.findOne that value it always returns null.

var name = Meteor.user().username;
var message = $('.action-textarea').val();
var userId = Meteor.userId();
var file = $("#input-photo").get(0).files[0];
if(file) {
    fsFile = new FS.File(file);
    var id = PostGeneralImages.insert(fsFile, function(err, result) { 
        if(err) {
            throw new Meteor.Error(err);
        } else { 
            var imageLoc = '/cfs/files/PostImages/' + result._id;
            PostImages.insert({
                    generalId: result._id,
                    userId: Meteor.userId(),
                    username: Meteor.user().username,
                    imageLoc: imageLoc
                });       
            }
        });
    }
var imagePath = PostImages.findOne({generalId: id._id}).imageLoc;
console.log(imagePath);

imagePath is undefined on console. But when I try findOne method in console it successfully returns the wanted object. I'm already publishing and subscribing that collection.

1

There are 1 answers

2
muetzerich On BEST ANSWER

solution for your problem:

get the result in the callback of the insert function cause insert works asynchronously.