gpt4 book ai didi

javascript - 从 MongoDB 文档返回字段的函数

转载 作者:行者123 更新时间:2023-12-03 06:05:09 24 4
gpt4 key购买 nike

我正在将 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 驱动程序来解决此问题。文档建议我需要采用面向回调或面向 promise 的方法,但我不知道这些方法意味着什么。

最佳答案

这是documentation中提到的promise语法。 :

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

关于javascript - 从 MongoDB 文档返回字段的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com