使用MongoClient更新不工作的NodeJ和MongoDB



我在mongodb大学上学习mongodb和nodejs课程,其中一项任务是找到任何状态下温度最高的文档,然后在其中添加一个字段"month_high"。我可以找到温度最高的状态的文档,但无法更新。代码如下。

有人能告诉我我可能做错了什么吗?

var MongoClient=require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/course',function(err,db){
var cursor=db.collection("weather").find();
cursor.sort({"State":1,"Temperature":-1});
var oldState,newState;  
cursor.each(function(err,doc){
    if(err)throw err;
    if(doc==null){
         return db.close();
    }
    newState=doc.State;
    if(newState!=oldState){
        var operator={'$set':{"month_high":true}};
            var query={"_id":doc._id};
            console.log(doc._id+" has temp "+doc.Temperature+" "+doc.State);
            db.collection("weather").update(doc,operator,function(err,updated){
                    console.log("hi");//---->Never Logs
                    if(err)throw err;
                   //   console.log(JSON.stringify(updated));
               })
    }   
    oldState=newState;
});


    });

我不能100%确定,但考虑到文档中报告的语法,即使不使用它,您也可能必须指定选项参数:

db.collection("weather").update(doc,operator, options, function(err,updated)

此外,在调用回调之前,连接可能会关闭。如果删除db.close()调用,它会改变什么吗?

集合名称为"data"。在本作业中,"天气"是数据库名称。

请参阅https://education.mongodb.com/courses/10gen/M101JS/2013_October/courseware/CRUD/Homework_2.2/

> use weather
switched to db weather
> db.data.findOne()

最新更新