How to accurately use foreach in nodejs for Mongodb operations

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

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 tried to do it db.collectionname.find().forEach(....), but I have an error saying that such a function does not exist. Please, help.

+4
source share
2 answers

The call find()to retrieve records from Mongo DB is asynchronous. You are trying to use documents before the data is available. You must have a loop forEachin the callback 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});
});
});

`

+4

each(), find():

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

- -

, mongojs, , Node.js , , :

// 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});
        });
    });
});
+2

Source: https://habr.com/ru/post/1614592/


All Articles