mongodb和nodejs中的promise待处理错误

问题描述 投票:0回答:5

我已经编写了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>

我不知道这个“承诺”是什么?请帮忙..

javascript node.js mongodb
5个回答
9
投票

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


2
投票

A promise 是在您等待实际值时给出的替代临时值。为了获得真正的价值

numItems.then(function (value) { callback(value) });

或者更好的是,从您的函数返回 Promise,并让他们使用 Promises 模式而不是回调模式来实现它。


1
投票

有同样的问题。不知道它是否仍然与您相关,但这就是我解决问题的方法:

var category = 'categoryToSearch';
var cursor = db.collection('item').find({'category':category});

cursor.count(function (err, num) {
    if(err) {
        return console.log(err);
    }
    return num;
});

0
投票

我试图解决类似的问题,让自己发疯,无论我做什么,

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 已列入白名单,不这样做有时也会导致问题。


0
投票

试试这个:

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

© www.soinside.com 2019 - 2024. All rights reserved.