2016-10-09 27 views
0

所以我有一個項目,我正在通過ID或名稱訪問數據庫表。在Express中使用承諾時檢索空數據

我的類路徑:

router.get('/name/:name', function(req, res) { 
    Category.fetchName(res, req.params.name); 
    console.log(res.name); 

}); 

我的類模型:

static fetchName(res, categoryName) { 
    categories.find({ 
     name: categoryName 
    }) 
    .then((doc) => { 
     res.send(doc); 
     console.log(doc); 

    }); 
} 

當我做console.log(doc)它打印出數組

[ { _id: 57f7d8382604126103f0113b, name: 'stuff' } ]

但是,當我訪問它在我的路線中,它表示undefined。我錯過了什麼?爲什麼我無法訪問從路由中的數據庫獲取的數據?

提前致謝!

回答

0

你不會得到res.name因爲你沒有在任何地方添加name propertyres對象。

router.get('/name/:name', function(req, res) { 
    Category.fetchName(res, req.params.name, function(err, result) { 
    if (!err) { 
     console.log(result); 
     res.send(result); 
    } 
    }); 
}); 


static fetchName(res, categoryName,callback) { 
    categories.find({ 
     name: categoryName 
    }) 
    .then((doc) => { 
     callback(null,doc); 
     console.log(doc); 
    }); 
} 
+0

仍然在我的路線不能訪問res.name,它這樣做時,我的模型...... – user2870415

+0

自異步問題你的承諾是不是還在說「不確定」,而我得到了正確的console.log結果working – abdulbarik

+0

我更新了我的答案,您可以現在檢查 – abdulbarik