I'm writing my own class to manage mongodb queries within express framework.
This how the class looks like
var PostModel = function(){};
PostModel.prototype.index = function(db){
db.open(function(err,db){
if(!err){
db.collection('post',function(err,collection){
collection.find().toArray(function(err,posts){
if(!err){
db.close();
return posts;
}
});
});
}
});
};
When I call this function:
// GET /post index action
app.get('/post',function(req,res){
postModel = new PostModel();
var posts = postModel.index(db);
res.json(posts);
});
I dont know why seems like the function index did not return anything.
But if I change the index function like this
var PostModel = function(){};
PostModel.prototype.index = function(db){
db.open(function(err,db){
if(!err){
db.collection('post',function(err,collection){
collection.find().toArray(function(err,posts){
if(!err){
db.close();
console.log(posts);
}
});
});
}
});
};
NOTE the console.log instead of the return. With this changes I can see into the terminal all the post I wanted. That's beacause the function retrive all the post as it should.
The problem is that it does not return the post :(
You're using async functions, they all get callbacks, so you'll need to use a callback too:
var PostModel = function(){};
PostModel.prototype.index = function(db, callback){
db.open(function(err,db){
if(!err){
db.collection('post',function(err,collection){
collection.find().toArray(function(err,posts){
if(!err){
db.close();
callback(posts);
}
});
});
}
});
};