Andrew Cooper
Andrew Cooper

Reputation: 15

Can't figure out promises with mongod and nodejs

I have a function getStuff() that needs to return the results of a query against MongoDB. I'm using nodejs and the mongod module. Here's the code I've got.

var mongo = require("mongod");
var url = "mongodb://localhost:27017/my-mongo";

function getStuff() {
    var db = new mongo(url, ["stuff"]);
    var promise = db.stuff.find()
        .then(function (result) {
            console.log(result);
            return result;
        }).done(function (data) {
            console.log(data);
            return data;
        });
    console.log(promise);
    return promise;
}

exports.getStuff = getStuff;

I'm obviously missing something about how promises work. I'm getting good data in the first two console.log() calls. However the getStuff() function always returns undefined. This seems like it should be a super simple use case but I'm banging my head on my desk trying to get it to work properly. Any help would be greatly appreciated.

Upvotes: 1

Views: 83

Answers (2)

Haris Hasan
Haris Hasan

Reputation: 30097

...that needs to return the results...

to get the data from getStuff

function getStuff(callback) {
    var db = new mongo(url, ["stuff"]);
    db.stuff.find()
    .done(function (result) {
            console.log(result);
            callback(result);
     }));
}

then you can call it like this

getStuff(function(data){
//here you will get your results
});

Upvotes: 1

Sze-Hung Daniel Tsui
Sze-Hung Daniel Tsui

Reputation: 2332

Your last log and return statement run as your .find.then.done chain are still being executed (that's Async for ya!). That's why promise is still undefined.

Try returning the entire promise, like instead of
var promise = db.stuff.find()... try
return db.stuff.find()...

Upvotes: 2

Related Questions