Updates to a record are not getting persisted in mongo database (nodejs + mongo)

Updates to a record are not getting persisted in mongo database (nodejs + mongo)


I have not found an answer so far (both with my own efforts and also online).

This is a NodeJS code snippet and uses mongodb in the backend.

In the code, I iterate over a (mongo) collection and update a particular field in each record.

I am unable to persist, changes to a record to the database.

Code :-

var mongoose = require('mongoose')

var Centers = mongoose.model('centers', new mongoose.Schema({
    "ChestClinic": String,
    "TestCenterName": String,
    "loc": {
       "type": {
       "lon": Number,
       "lat": Number
     "index": '2d'


Centers.find({}, function(err, recs) {
    var me = this
    async.forEachSeries ( recs, function(rec, callback) {
        var loc = { lon: 100, lat: 100 };
        rec.setValue ( 'loc', loc);
        rec.save ( function (err, rec) {
            if ( !err ) {
               console.log( rec );
            } else {
               console.log ( 'Error while saving' );
    }, function(err) {
        console.log ( '\ncomplete' );

When I open this database in shell using mongo command, the values that i see for “loc” are still 0, 0 (instead of 100,100).

Appreciate any suggestions towards fixing it.

Thanks Naval

Problem courtesy of: flipflopapp


loc is a mixed type field. When you change those, Mongoose needs to be told the field has changed before saving:

rec.setValue('loc', loc);

Why that is is explained here.

Solution courtesy of: robertklep


Leave a Reply

Your email address will not be published. Required fields are marked *