Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mongoose Promise - mongo

Can someone give me an example on how to use a Promise with mongoose. Here is what I have, but its not working as expected:

app.use(function (req, res, next) {   res.local('myStuff', myLib.process(req.path, something));   console.log(res.local('myStuff'));   next(); }); 

and then in myLib, I would have something like this:

exports.process = function ( r, callback ) {   var promise = new mongoose.Promise;   if(callback) promise.addBack(callback);    Content.find( {route : r }, function (err, docs) {      promise.resolve.bind(promise)(err, docs);    });    return promise;  }; 

At some point I am expecting my data to be present, but how can I access it, or get at it?

like image 701
user600314 Avatar asked Jan 26 '12 17:01

user600314


People also ask

Does Mongoose use promise?

If you're an advanced user, you may want to plug in your own promise library like bluebird. Just set mongoose. Promise to your favorite ES6-style promise constructor and mongoose will use it.

Does Mongoose return a promise?

While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.

What is MongoDB promise?

A Promise is an object returned by the asynchronous method call that allows you to access information on the eventual success or failure of the operation that they wrap.


1 Answers

In the current version of Mongoose, the exec() method returns a Promise, so you can do the following:

exports.process = function(r) {     return Content.find({route: r}).exec(); } 

Then, when you would like to get the data, you should make it async:

app.use(function(req, res, next) {      res.local('myStuff', myLib.process(req.path));      res.local('myStuff')          .then(function(doc) {  // <- this is the Promise interface.              console.log(doc);              next();          }, function(err) {              // handle error here.          }); }); 

For more information about promises, there's a wonderful article that I recently read: http://spion.github.io/posts/why-i-am-switching-to-promises.html

like image 140
Alexander Shtuchkin Avatar answered Oct 21 '22 22:10

Alexander Shtuchkin