从MongoDB文档中返回字段

Function To Return Field from MongoDB Document

本文关键字:返回 字段 文档 MongoDB      更新时间:2023-09-26

我使用MongoDB与Node.js。我想做一个函数,我可以调用一些基本值的参数(以识别文档),然后是我希望函数返回值的字段名。

我的文档是这样的:

{
    "name": "John Smith",
    "email": "john.smith@gmail.com",
    "phone": "555-0125"
}

我想这样调用函数:

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

我如何使用MongoDB的Node.js驱动程序。文档建议我将需要采取面向回调或面向承诺的方法,但我不知道这两个东西是什么意思。

这是文档中提到的承诺语法:

// 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()被调用时,它返回一个游标对象,它允许你过滤/选择/读取查询结果。由于find()是异步(延迟执行)调用,javascript必须附加一个回调,当find()的结果被解决时将被执行。

MDN也有更多关于Promise对象的信息在这里进一步阅读:承诺

对于您的代码,您可以这样做:

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

您可以使用co生成器。它的工作原理很容易理解。

//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();
}

如果你想

,你也可以使用本机回调