0

I wish to update a Mongo collection in some code that looks like this:

var Q = Npm.require('q');
var db = new Mongo.Collection('mydb');

function doSomething() {
    var d = Q.defer();
    setTimeout( function() {
        d.resolve();
    }, 1000);
    return d.promise;
}

doSomething().then( function() {
    console.log('before find');
    var records = db.find({}).fetch(); // blocking operation never completes
    console.log('after find');
    console.log(records); // should be []
});

When running meteor with the above code, it will get as far as logging "before find" but then the execution is halted waiting for db.find to complete. It never completes.

Are there any solutions or workarounds for this?

Update: it seems to be the .fetch() that causes the issue. I need this part though, I want to manipulate the data I am receiving from Mongo.

Aaron Cunnington
  • 1,631
  • 2
  • 15
  • 23
  • Using promises in meteor server code is not really idiomatic. If you're using an npm package which exports promises, extract them synchronously using this: http://stackoverflow.com/questions/23773057/a/23777507 . Otherwise you could try wrapping your `then` callback in `Meteor.bindEnvironment`, as in `.then(Meteor.bindEnvironment(function () {...}))` – user3374348 Aug 07 '15 at 15:15

1 Answers1

1

Instead of using fetch, add a callback function. It will allow you to manipulate the data after its retrieved:

var records = db.find({}, function(error, data){

        // Do something with your data here
});

** Edit - with the callback above, a curser is returned. If you want to return an Array with the results, use the following:

 var records = db.find({}).toArray(function(error, data){

        // Do something with your data here
});
Stacey Burns
  • 1,092
  • 7
  • 14