4

This is my code to get the data from a collection groupname which is initialised with the name of collection. I want to iterate the data stored in doc using foreach loop.

var db = mongojs('login');

    var cursor = db.collection(groupname).find();
    console.log(cursor);

    cursor.each(function(err, doc) {
        console.log(doc._id);

        mongo.collection(doc._id + "group", function(err, collection) {
            collection.remove({"groupname": groupname});
        });
    });

I've tried doing db.collectionname.find().forEach(....), but I've got an error saying that such function doesn't exists. Please help.

Nick K
  • 379
  • 1
  • 3
  • 18
sachin hunur
  • 281
  • 2
  • 6
  • 17

2 Answers2

6

The find() call to fetch the records from Mongo DB is asynchronous. You are trying to use the docs even before the data is available. You should have your forEach loop in the call back of the find().

`

db.collection(groupname).find({}, function(err, doc){
console.log(doc);
doc.forEach(function(err,doc){
    console.log(doc._id);
    db=mongo.collection(doc_id+"group");
    db.remove({"groupname":groupname});
});
});

`

UserStack
  • 104
  • 1
  • 4
  • I tried using your code. The code executes but nothing happens. The control does not enter the function(err,doc). Any idea why? – sachin hunur Nov 05 '15 at 11:25
  • hey I realised where i was going wrong. I was deleting the collection before it could select the data. Now i get the message on console which shows the value for doc._id as undefined. – sachin hunur Nov 05 '15 at 11:35
2

Use the each() method to iterate over all the documents for the find() cursor:

// Grab a cursor
var cursor = db.collection(groupname).find();
console.log(cursor);

// Execute the each command, triggers for each document
cursor.each(function(err, doc) {
    console.log(doc._id);
    // Fetch a collection to remove document
    mongo.collection(doc._id + "group", function(err, collection) {
        collection.remove({"groupname": groupname});
    }
});

-- UPDATE --

Seeing that you are using the mongojs library after your edit, you need to pass a callback function to handle the results of the query since Node.js implements an asynchronous paradigm and almost everything is always a callback which allows your app to be non-blocking and high performing:

// connect now, and worry about collections later
var db = mongojs('login')
var groupcollection = db.collection(groupname)

groupcollection.find({}, function(err, groups) {
    if( err || !groups) console.log("No groups found");
    else groups.forEach( function(group) {
        console.log(group);
        mongo.collection(group._id + "group", function(err, collection) {
            collection.remove({"groupname": groupname});
        });
    });
});
chridam
  • 100,957
  • 23
  • 236
  • 235