在mongodb和nodejs中承诺挂起错误
我已经写了node.js代码来获取一些使用MongoDB的数据库。这是我的代码
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代码是asynchronous的,因此numItems
不会包含项目的计数 – 它包含Promise
,其中包含parsing时的项目数量。 你不得不掌握node.js和asynchronous编程的基础知识。 尝试像这样修改你的代码
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) });
或者更好的是,从你的函数中返回promise,让它们使用Promises模式来实现它,而不是callback模式。
有同样的问题。 不知道它是否与你有关,但这是为我解决的:
var category = 'categoryToSearch'; var cursor = db.collection('item').find({'category':category}); cursor.count(function (err, num) { if(err) { return console.log(err); } return num; });