Reputation: 684
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..
Upvotes: 5
Views: 22276
Reputation: 2046
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 definitely 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
Upvotes: 9
Reputation: 1
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
)
Upvotes: 0
Reputation: 344
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:
(req,res)
to async(req,res)
.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.
Upvotes: 0
Reputation: 339
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;
});
Upvotes: 1
Reputation: 6998
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.
Upvotes: 2