简体   繁体   中英

promise pending error in mongodb and nodejs

I have written node.js code for getting some number using mongodb database.this is my code for that

    MongoClient.connect('mongodb://localhost:27017/mongomart', function(err, db) {

    assert.equal(null, err);

    var numItems=db.collection('item').find({"category":category}).count();

    callback(numItems);
});

This mongodb query runs correct on mongo shell but it is giving error when using with node.js

Promise <Pending>

I don't know what is this "promise" ? Please help..

node.js code is asynchronous so that numItems won't contain count of items - it rather contains Promise that contains count of items when resolved. You defenetely have to master the basics of node.js and asynchronous programming. Try to modify your code like this

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

For native Promise check out documentation https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise

Also look at bluebird promises https://github.com/petkaantonov/bluebird

A promise is a substitute temporary value that is given while you wait on the real value. To get the real value do

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

Or better yet, return the promise from your function, and let they implement it using the Promises pattern, instead of the callback pattern.

Had the same problem. Don't know if it's still relevant to you, but this is what solved it for me:

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

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

I drove myself bananas trying to solve a similar problem, where the document.save() option just gave Promise{pending} no matter what I did. Here's what I did:

  • Change (req,res) to async(req,res) .
  • Change var post = doc.save() to var post = await doc.save() .

Finally, log in to MongoDB web, and change accessible IP addresses to 0.0.0.0 (all addresses). Not doing this can cause issues sometimes even when your IP is whitelisted.

try this:

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

(adding the await and turn this function to async function )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM