Prasad Silva
Prasad Silva

Reputation: 1042

Mongoose save after find not working (data migration script)

I'm trying to perform a one-off migration of the data in a collection, and I'm attempting to use find() with a forEach save operation on the returned array. But save() isn't doing (the collection in the db isn't updated) and the error callback is not fired. The data returned by find() is valid. What am I missing?

Patient.find().exec(function(err, patients) {
    console.log('Data: ' + patients.length);  // The patients array is valid

    patients.forEach(function(patient) {
        console.log(patient.name);  // Prints valid data
        patient.name = patient.name + ' (*)';
        patient.save(function(err) {
            console.err(err);  // This callback is never called
            process.exit(1);
        });
    });

    process.exit(0);
});

Upvotes: 0

Views: 134

Answers (1)

Prasad Silva
Prasad Silva

Reputation: 1042

The issue was the process.exit(0) call at the end. I had forgotten that the save call was async and the exit call at the end quit the script before the queued save operations ran. I restructured the code so that the script would exit only after all save operations have completed. Now I get the correct behavior. If there is a better way to structure this code, then please share.

Patient.find().exec(function(err, patients) {
    console.log('Data: ' + patients.length);

    var doneCount = 0;
    patients.forEach(function(patient) {
        patient.name = patient.name + ' (!)';
        patient.save(function(err) {
            if (err) {
                console.log(errorHandler.getErrorMessage(err));
                process.exit(1);
            }
            doneCount++;
            console.log('Completed ' + doneCount + '/' + patients.length + ' updates');
            if (doneCount == patients.length) {
                console.log('Done!');
                process.exit(0);
            }
        });
    });
});

Upvotes: 1

Related Questions