简体   繁体   English

游标,MongoDB和Nodejs中的替换更新

[英]Replacement update within cursor, MongoDB and Nodejs

This is the second time I've ran into this problem so it must be me that's doing something wrong. 这是我第二次遇到此问题,所以一定是我做错了什么。 I create a cursor that contains all the docs of my collection with a projection, and want to iterate through this cursor so I can update my collection. 我创建了一个游标,其中包含我的收藏中所有带投影的文档,并且想要遍历此游标,以便可以更新我的收藏。

For example, I sort my cursor so I can view my data differently, and based on how it's sorted I can make informed decisions on how to update a doc or even remove it... but it doesn't seem to work. 例如,我对光标进行了排序,以便可以以不同的方式查看我的数据,并且根据数据的排序方式,我可以就如何更新文档甚至删除文档做出明智的决定……但它似乎不起作用。

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

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

    //Remove 
    doc.scores.splice(3, 1);

    query2 = {"_id":doc._id};

    db.collection('highscores').update(query2, doc, function(err, updated) {
                if(err) throw err;

                console.dir("Updated Doc" + doc._id);


             });

    console.dir(doc);

Is there a more efficient way of doing this or am I missing something? 有没有更有效的方法可以做到这一点?

As is typical with NodeJS modules, and especially the MongoDB driver for NodeJS, most commands and actions are asynchronous. 如典型的NodeJS模块,尤其是NodeJS的MongoDB驱动程序,大多数命令和动作都是异步的。

So, your code was using db.close when the cursor had been exhausted. 因此,当游标耗尽时,您的代码正在使用db.close While some of the updates in the loop may have been able to complete, it's just as likely that the database connection was closed before any actually had a chance to update. 尽管循环中的某些更新可能已经完成,但在任何实际有机会更新之前,数据库连接很可能已关闭。

You should just exit from the each function block by using return in the example you provide. 您应该通过在提供的示例中使用return来退出each功能块。

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

    if(doc === null) {
        return;
    }

    //Remove 
    doc.scores.splice(3, 1);

    var query2 = {"_id": doc._id};

    db.collection('highscores').update(query2, doc, function(err, updated) {
       if(err) throw err;
       console.dir("Updated Doc" + doc._id);
    });

    console.dir(doc);
});

Also, you might want to take at look at the update operator $set , which would potentially optimize the update operation you're performaning ( reference ). 另外,您可能想看一下update操作符$set ,它可能会优化正在执行的更新操作( 参考 )。 It "sets" only the values you specify for a document rather than updating the entire document in the collection. 它仅“设置”您为文档指定的值,而不更新集合中的整个文档。

Take a look at the array operators as well -- they might be useful in the specific case you're working on. 还要看一下数组运算符 -在您正在处理的特定情况下,它们可能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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