0

I'm trying to count the number of documents in a collection and then use the result into another insert query using Node.js.

var number;
db.collection("collection").countDocuments({}, function(error, numOfDocs){
    if(error) throw error;
    else{
        console.log(numOfDocs);
        number = numOfDocs;
    }
}); 

var myobj = { num: "Number_"+number };
db.collection("another_collection").insertOne(myobj, function(err, res) 
{
    if (err) throw err;
    console.log("1 document inserted");         
});

The inserted value in the collection is { "num" : "Number_undefined" }

How to use the result of the first query into another?

1 Answer 1

2

It is because you have not given Number a value. Further, the count() function is a async function (I wrote an answer here about that). Try this:

db.collection('collection')
  .countDocuments({}, function(error, numOfDocs){
    if(error) throw error;
    else {
        var myobj = { num: 'Number_' + numOfDocs };
        db.collection('another_collection').insertOne(myobj, function(err, res) {
               if (err) throw err;
               console.log('1 document inserted');         
        });
    }
}); 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @weirdpanda. But this generates an error "MongoError: server instance pool was destroyed". Any idea why this is happening?
It's not because of this code. Are you using db.close() somewhere after this bit?
Thanks, it worked. I was using db.close() Removed that and it works fine now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.