Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how exactly to use foreach in nodejs for Mongodb operations

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.

like image 200
sachin hunur Avatar asked Feb 08 '23 15:02

sachin hunur


2 Answers

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

`

like image 50
UserStack Avatar answered Feb 12 '23 02:02

UserStack


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});
        });
    });
});
like image 40
chridam Avatar answered Feb 12 '23 03:02

chridam