getglad
getglad

Reputation: 2562

MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage

I am trying to upsert a dataset to a Mongo collection.

When I run the below code, I am getting an error: MongoError: The dollar ($) prefixed field '$push' in '$push' is not valid for storage.

I put this together based on the docs: https://docs.mongodb.org/getting-started/node/update/#update-multiple-documents

Versions: MongoDB (windows) = 3.2.0; mongodb (npm package) = 2.1.4

var query = {
 county: aCountyName, 
 state: aStateName
}    

var params = {
 '$set': {     
  county: 'Boone',
  state: 'MO',
  '$push': {
    zips: {
      '$each': [ '65203' ]
    }
  }
 }
}

(could also be)

var params = {
 '$set': {     
  county: 'Pierce',
  state: 'WA',
  '$push': {
    zips: {
      '$each': [ '98499', '98499' ]
    }
  }
 }
}

db.collection(collectionName).updateMany(query, params, {'upsert': true},
  function(err, results) {
    callback();
  }
);

Upvotes: 23

Views: 40448

Answers (2)

Sede
Sede

Reputation: 61225

The reason is because you didn't close the } so MongoDB think $push is a field's name and as mentioned in the documentation:

Field names cannot contain dots (i.e. .) or null characters, and they must not start with a dollar sign (i.e. $).

var query = {
 county: aCountyName, 
 state: aStateName
};

var params = {};
params['$set'] = { county: 'Boone', state: 'MO' };
params['$push'] = { zips: { '$each': [ '65203' ] } };

Then:

db.collection(collectionName).updateMany(query, params, {'upsert': true},
  function(err, results) {
    callback();
  }
);

Upvotes: 2

Owain Williams
Owain Williams

Reputation: 2617

I don't think $push is valid within a $set. Instead try adding it as another parameter, e.g.:

var params = {
  '$set': {
    county: 'Pierce',
    state: 'WA'
  },
  '$push': {
    zips: {
      '$each': ['98499',
      '98499']
    }
  }
}

Upvotes: 33

Related Questions