Akshat Yadav
Akshat Yadav

Reputation: 33

Using result of one query in another query : nodejs and mongodb

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?

Upvotes: 0

Views: 488

Answers (1)

weirdpanda
weirdpanda

Reputation: 2626

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

Upvotes: 2

Related Questions