![](/img/trans.png)
[英]MongoDB connection with nodejs returns promise <pending>
[英]promise pending error in mongodb and nodejs
我已經編寫了使用 mongodb 數據庫獲取一些數字的 node.js 代碼。這是我的代碼
MongoClient.connect('mongodb://localhost:27017/mongomart', function(err, db) {
assert.equal(null, err);
var numItems=db.collection('item').find({"category":category}).count();
callback(numItems);
});
此 mongodb 查詢在 mongo shell 上運行正確,但與 node.js 一起使用時出錯
Promise <Pending>
我不知道這個“承諾”是什么? 請幫忙..
node.js 代碼是異步的,因此numItems
不會包含項目數 - 它包含Promise
,在解決時包含項目數。 你必須掌握 node.js 和異步編程的基礎知識。 嘗試像這樣修改您的代碼
MongoClient.connect('mongodb://localhost:27017/mongomart', function(err, db) {
assert.equal(null, err);
db.collection('item').find({"category":category}).count()
.then(function(numItems) {
console.log(numItems); // Use this to debug
callback(numItems);
})
});
對於原生Promise
,請查看文檔https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise
另請查看bluebird
承諾https://github.com/petkaantonov/bluebird
承諾是在您等待實際值時給出的替代臨時值。 要獲得真正的價值
numItems.then(function (value) { callback(value) });
或者更好的是,從您的函數返回承諾,並讓他們使用 Promises 模式而不是回調模式來實現它。
有同樣的問題。 不知道它是否仍然與您相關,但這就是為我解決的問題:
var category = 'categoryToSearch';
var cursor = db.collection('item').find({'category':category});
cursor.count(function (err, num) {
if(err) {
return console.log(err);
}
return num;
});
我開車試圖解決一個類似的問題,無論我做什么, document.save()
選項都會給出Promise{pending}
。 這是我所做的:
(req,res)
更改為async(req,res)
。var post = doc.save()
更改為var post = await doc.save()
。 最后,登錄 MongoDB web,將可訪問的 IP 地址更改為0.0.0.0
(所有地址)。 即使您的 IP 被列入白名單,不這樣做有時也會導致問題。
嘗試這個:
MongoClient.connect('mongodb://localhost:27017/mongomart', async (err, db) => {
assert.equal(null, err);
var numItems= await db.collection('item').find({"category":category}).count();
callback(numItems);
});
(添加await
並將此功能轉換為async function
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.