【发布时间】:2016-11-15 19:36:28
【问题描述】:
我有以下代码(不能按预期工作):
var express = require('express')
var app = express()
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/interviews';
app.get('/', function(req, res){
var result = get_document(res);
res.send( result // show the results of get document in the browser //)
console.log("end");
});
app.listen(3000, function(req, res) {
console.log("Listening on port 3000");
});
function get_document() {
MongoClient.connect(url, function(err, db) {
var col = db.collection('myinterviews');
var data = col.find().toArray(function(err, docs) {
db.close();
return docs[0].name.toString(); // returns to the function that calls the callback
});
});
}
函数“get_document”应该返回存储在“myinterviews”集合中的文档。问题是'return docs [0] ...'行返回到col.find(这是调用回调的函数)而不是app.get(...)中的变量'result'。
你知道如何让文档返回'result'变量吗?
【问题讨论】: