如何在node.js中设置一个mongoDB游标?

时间:2013-11-04 14:53:52

标签: node.js mongodb set

我有一个mongoDB集合,我希望使用$set在随机位置添加字段,至少我很确定它是$set。如果我错了,请纠正我。 我包括代码。在中间,我包括我想要做的评论:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) {

    // Also, what is the best way to handle err in this code?
    //if(err) throw err;

    var query = { };
    var sortorder = {"State":1, "Temperature":-1}

    var xx = null;

    //var cursor = db.collection('data').find();
    var cursor = db.collection('data').find().sort(sortorder);

    cursor.each(function(err, doc) {
        //if(err) throw err;

        if(doc == null) {
            return db.close();
        }


        if (xx == doc.State){


        }else{

                console.dir("New state -----------" + doc.State);
                console.dir("Tempurature -----------" + doc.Temperature);

                // !!!!!!!!!!!!!!!!!!!!!!!!!!   this is the problem area.
                //--- this is the part I am trying to figure out...
                update_routine = $set:{"month_high---test001":true};
                doc.update =  update_routine;
                //  How do I do a $set operation on a mongoDB cursor.  which I have here.
                xx = doc.State;
                // add the field
                //doc.update();

        }

        if(doc == null) {
            return db.close();
        }

    //app.error(function(err, req, res, next){
    //  console.error(err);
    //  res.send('Fail Whale, yo.');
    //});

        //console.dir(doc.State + " is a state!");
    });
});

~~

1 个答案:

答案 0 :(得分:3)

你的代码看起来有点混乱,但这是你可以做的。 另请查看$ set:http://docs.mongodb.org/manual/reference/operator/update/set/

的mongodb文档
var cursor = db.collection('data').find().sort(sortorder);

cursor.each(function(err, doc) {
    if(err) throw err;

    if(doc == null) {
        return db.close();
    }

    // until here you code makes sense, you have a cursor, 
    // you checked for errors and have the current document

   // now you want to update a record, you can do it like this:

   var myquery = {};
   myquery['_id'] = doc['_id'];

   // you were missing the surrounding {}
   var myupdate = { $set: { field1: "whatever value", field2: 500 } }; 
   // obviously you want to replace field1 and field2 with your actual field names

   // instead of creating a new update object and using $set
   // you could also just modify the 'doc' variable and pass it again 
   // in the update function below instead of myupdate


   db.collection('data').update(myquery, myupdate, function (err, updatedDoc) {
      if (err) throw err;
      console.log("successfully updated document", updatedDoc);
    });

});