Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

node.js - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...