Larsmanson
Larsmanson

Reputation: 413

Using promises in Mongoose

I am new to the Promise method used to retrieve multiple database records at the same time and I want to rewrite my existing code to use promises

I have this piece of code in Express:

getController.getData = function(req,res, collection, pagerender) {
  var id = req.params.id;
  collection.find({}, function(err, docs){
    if(err) res.json(err);
    else res.render(pagerender, {data:docs, ADusername: req.session.user_id, id: req.params.id});
    console.log(docs);
  });
};

Now I want to use promises here, so I can do more queries to the database. Anyone know how I can get this done?

Upvotes: 0

Views: 28

Answers (1)

Jure Malovrh
Jure Malovrh

Reputation: 314

First, check if collection.find({}) returns a promise. If it does, then you can call your code like:

collection.find({}).
    then(function(docs){
        res.render(pagerender, {data:docs, ADusername: req.session.user_id, id: req.params.id});
    })
    .catch( function(err) {
        res.json(err);
    })

If you want more calls here, just create new DB call and add another .then block.

I suggest you read the documentation on promises, just to get a general feeling about them (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then). You will also see how you can handle both success and rejection in the same function if you want.

Upvotes: 1

Related Questions