How to use “q” module for refactoring mongoose code?

后端 未结 5 508
野趣味
野趣味 2020-12-31 04:30

I\'m using mongoose to insert some data into mongodb. The code looks like:

var mongoose = require(\'mongoose\');
mongoose.connect(\'mongo://localhost/test\')         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-31 04:44

    Considering Model.save instead of Collection.insert (quite the same in our case).

    You don't need to use Q, you can wrap yourself the save method and return directly a Mongoose Promise.

    First create an utility method to wrap the save function, that's not very clean but something like:

      //Utility function (put it in a better place)
      var saveInPromise = function (model) {
    
        var promise = new mongoose.Promise();
    
        model.save(function (err, result) {
          promise.resolve(err, result);
        });
    
        return promise;
      }
    

    Then you can use it instead of save to chain your promises

      var User = mongoose.model('User');
      var Channel = mongoose.model('Channel');
      var Article = mongoose.model('Article');
    
      //Step 1
      var user = new User({data: 'value'});
      saveInPromise(user).then(function () {
    
        //Step 2
        var channel = new Channel({user: user.id})
        return saveInPromise(channel);
    
      }).then(function (channel) {
    
        //Step 3
        var article = new Article({channel: channel.id})
        return saveInPromise(article);
    
      }, function (err) {
        //A single place to handle your errors
    
      });
    

    I guess that's the kind of simplicity we are looking for.. right? Of course the utility function can be implemented with better integration with Mongoose.

    Let me know what you think about that.


    By the way there is an issue about that exact problem in the Mongoose Github:

    • Add 'promise' return value to model save operation

    I hope it's gonna be solved soon. I think it takes some times because they are thinking of switching from mpromise to Q: See here and then here.

提交回复
热议问题