简体   繁体   中英

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.

So, your code was using db.close when the cursor had been exhausted. 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.

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 ). 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.

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