2016-09-19 152 views
0

我正在使用MongoDB和Node.js.我想創建一個函數,我可以調用一些基本值的參數(以標識文檔),然後我希望函數返回值的字段名稱。函數從MongoDB返回字段文檔

我的文件是這樣的:

{ 
    "name": "John Smith", 
    "email": "[email protected]", 
    "phone": "555-0125" 
} 

我要調用的函數是這樣的:

var phone_number = GetInfo({"name":"John Smith"}, "phone"); 
console.log(phone_number); // This should output "555-0125" 

我如何去使用這個Node.js的驅動程序MongoDB的。文檔表明我需要採取面向回調或面向Promise的方法,但我不知道這些事情是什麼意思。

回答

1

這是在documentation提到的承諾語法:

// Retrieve all the documents in the collection 
collection.find().toArray(function(err, documents) { 
    test.equal(1, documents.length); 
    test.deepEqual([1, 2, 3], documents[0].b); 

    db.close(); 
}); 

find()被稱爲通知,它返回一個Cursor Object它可以過濾/選擇/讀取查詢的結果。由於find()是一個異步(延遲執行)調用,因此javascript必須附加一個回調函數,該函數在解決find()的結果時執行。

MDN也有關於Promise對象這裏進一步閱讀的更多信息:Promises

在你的代碼的情況下,你可以這樣做:

// collection defined above this code snippet. 
collection 
    .findOne({"name":"John Smith"}) 
    .forEach(function(doc) { console.log(doc.phone) }); 
0

您可以使用co generator這一點。很容易理解它是如何工作的。

//your function call 
var phone_number = GetInfo({"name":"John Smith"}, {"phone":1}); 

//your function description 
function GetInfo(query, projection) { 
    //using generator 
    co(function*() { 
    //connect to db 
    let db = yield MongoClient.connect(url); 
    let collectionName = db.collection(colName); 
    collectionName.find(query, projection).toArray((err, doc)=> { 
     if (err) console.log(err); 
     //your data 
     console.log(doc); 
    return doc; 
} 
db.close(); 
} 

您還可以,如果你想

+0

喜用這個本地回調 - 我想這一點。該文檔打印良好,但phone_number的值仍未定義。 – SNB

相關問題