Collect data recursively in nodejs and then delete it one by one

129 Views Asked by At

infom_col is a collection which contains a field rkey which itself contains an array like this: rkeys -> brands so brands is an array of ids. These ids are reference to other documents in the collection. I need to collect all such dependent ids and delete the documents one by one.

This is my code. Throws an error: TypeError: Cannot read property 'rkeys' of undefined

function collect_data(id)
{
  db.infom_col.find({"_id":id}, function(err,doc) {
        if(err) throw err;
        else 
        {
          console.log("else: " + doc._id);
          console.log("length: " + doc.rkeys.length);
          if(typeof(doc[0].rkeys) != 'undefined' && doc[0].rkeys != null) {
               for(key in doc[0].rkeys){
                   doc[0].rkeys[key].forEach(function(entry) {
                  //console.log("entry: " + entry); 
                     ids.push(entry);
                  //console.log(ids);
                   });
                }
                if(ids.length > 0) {
                    var id1 = ids.pop();
                    console.log(id1);
                    db.infom_col.remove({"_id":id1}, function(err,doc1) {
                        if(err) throw err;
                        else {
                          console.log("deleted: " + id1);
                          var id2 = ids.shift();
                          console.log("going to delete: " + id2);
                          collect_data(id2,null);
                        } 
                    });
                }
            }
        } 
    });
 }

Update1:

function collect_data(id,cb)
{
   db.infom_col.findOne({"_id":id}, function(err,doc) {
       if(err) throw err;
       else 
       {
          console.log("else: " + doc._id);
          if (doc.rkeys) {
               console.log("length: " + doc.rkeys.length);
               for(key in doc.rkeys){
                  doc.rkeys[key].forEach(function(entry) {
                      console.log("entry: " + entry);
                      ids.push(entry);
                  });
               }
               if(ids.length > 0) {
                  var id1 = ids.shift();
                  console.log("id1: " + id1);
                  db.infom_col.remove({"_id":id1}, function(err,doc1) {
                        if(err) throw err;
                        else collect_data(id1,null); 
                  });
               }
       }
   } 
 });
}
1

There are 1 best solutions below

8
On

The error you are having: TypeError: Cannot read property 'rkeys' of undefined means that doc[0] is undefined.

First I would change the find to findOne:

db.infom_col.findOne({"_id":id}, function(err,doc) {

Then I would get rid of doc[0], because it's confusing.

After that, determine if doc.rkeys is set:

if (doc.rkeys.length > 0)

or, with underscore:

if (!_.isEmpty(doc.rkeys))