2015-10-13 13 views
0

我正在與Mongoose和MongoDB一起使用MMEAN堆棧。我想測試集合Foo是否爲空,但它涉及一個帶回調的Mongoose find()函數。 我不熟悉回調函數,所以我想知道如何從回調函數中獲取一條信息到其父函數中。如何將回調內部的結果傳遞給其父函數?

這是我必須遵循addFoo邏輯: 1.檢查美孚集合爲空 2.如果foo是空的,保存新文檔的Foo 3. 如果富不爲空,不救新的Foo文檔

我正在從routes/index.js調用save方法addFoo()

// routes/index.js 
router.post('/foo', function(req, res, next){ 
    var foo = new Foo(req.body); 
    foo.addFoo(function(err, bid){ 
    if(err){ return next(err); } 
    res.json(foo); 
    }); 
}); 

// models/Foo.js 

var mongoose = require('mongoose'); 
var FooSchema = new mongoose.Schema({ 
    creator: String 
}); 
mongoose.model('Foo', FooSchema); 

FooSchema.methods.addFoo = function(cb){ 

    // finds all documents of Foo into the "results" array 
    this.model("Foo").find(function(err, results){ 
    if (err){return err;} 
    // if the Foo results array is empty 
    if (results.length == 0){ 
     // HOW DO I LET addFOO() KNOW THAT THE ARRAY IS EMPTY? 
     // somehow pass the boolean out to addFoo() 
    } 
    }); 

    // IF Empty 
    // this.save(cb); 

} 

回答

1

這將工作如下...

FooSchema.methods.addFoo = function(cb){ 
    var that = this; 
    this.model("Foo").find(function(err, results){ 
    if (err){return err;} 
    // if the Foo results array is empty 
    if (results.length == 0){ 
     that.save(cb); 
    } 
    }); 
} 

但是如果你想要將它傳遞給家長,按您的實際需要,那麼你可以嘗試如下....

FooSchema.methods.addFoo = function(cb){ 
     var that = this; 
     this.model("Foo").find(function(err, results){ 
     if (err){return err;} 
     // if the Foo results array is empty 

      that.commit(!results.length);//Calling a parent function from inside callback function 

     }); 

     function commit(doCommit){ 
     if(doCommit) { 
      that.save(cb); 
     } 
     } 
    } 
1

簡而言之:你沒有。

回調在addFoo函數結束後執行。你基本上把你的函數的其餘部分放在回調中。

由於您需要訪問this,您可以通過var self = this;將其綁定到變量,然後在回調中使用self

另一種選擇是使用promises和denodeify函數,該函數將回調請求函數轉換爲返回函數Promise

相關問題