LucasSeveryn
LucasSeveryn

Reputation: 6272

Iterate over every document in mongodb from nodejs

My current code:

  var cursor = db.get('unameMap').find()
  cursor.forEach(function(doc){  
      console.log("considering: " + doc)
  });

All other requests to the database work, so assume var db is defined correctly.

For some reason this code doesn't produce anything in the console, tried it on a few different collections and it just doesn't do anything.

All other mongo code such as .aggregate works fine

Ultimately I want to do this (update a property on every document in a collection)

var cursor = db.get('unameMap').find()
  cursor.forEach(function(doc){  
      console.log("considering: " + doc)
      doc.testProperty="newValue"
      db.get('unameMap').save(doc);
  });

Upvotes: 1

Views: 2067

Answers (2)

LucasSeveryn
LucasSeveryn

Reputation: 6272

This works:

db.get('unameMap').find({}).each(function(doc,err){
      console.log("-------considering: ")
      console.log(doc)
      doc.testProperty="newValue"

      db.get('unameMap').update(
                  {                              
                   "uname" : doc.uname,
                   "name" : doc.name
                  },                                
                  {
                    $set : entry,
                  },
                  {
                    upsert: true,
                    writeConcern: { w: 0 }
                  }, 
                  function(err, result) {
                    if(err === null){                                    
                        console.log("uname map - added: " + doc.name);                                    
                    }else{
                        console.log(err)
                    }
                  }
              );
})

Upvotes: 0

hya
hya

Reputation: 1738

Try with this code, but I think db.get('unameMap') does not return Schema model of unameMap. Refering to Mongoose documentation it returns Mongoose options, but they dont say much more about this. I'd suggest you to include you Schema model and use it instead of db.get(...).

Here is example of cursor:

var MyModel = require('./unamemap');

var cursor = MyModel.find().cursor();

next(cursor.next);

function next(promise) {
  promise.then(function(doc) {
    if (doc) {
      console.log("considering: " + doc);
      doc.testProperty="newValue";
      doc.save(doc);
      next(cursor.next());
    }
  });
}

Upvotes: 1

Related Questions