简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM