0

When trying to update data in a NeDB database I'm getting Field names cannot begin with the $ character however it only happens after the second or third time updating the DB.

Here's the code I'm using to update/insert data:

addNew: function(data) {
  var deferred = $q.defer(),
      query = {
        _id: data._id,
        title: data.title,
        year: data.year,
        genres: data.genres,
        poster: data.poster
      };

  db.update(query, { $addToSet: { episodes: data.episodes[0] } }, { upsert: true }, function(err, numReplaced, upsert) {
    if (!err) {
      var data = numReplaced + '/' + upsert;
      deferred.resolve(data);
    } else {
      deferred.reject(err);
    }
  });

  return deferred.promise;
}

data.episodes[0] looks like this:

{
  "number": 5,
  "season": 3,
  "title": "Kissed by Fire",
  "overview": "The Hound is judged by the gods. Jaime is judged by men. Jon proves himself. Robb is betrayed. Tyrion learns the cost of weddings.",
  "screen": "http://slurm.trakt.us/images/episodes/1395-3-5.80.jpg"
}

The data in the DB I'm trying to update looks like this:

{
  "_id": "tt0944947",
  "title": "Game of Thrones",
  "year": 2011,
  "genres": "Drama, Fantasy, Adventure",
  "poster": "http://slurm.trakt.us/images/posters/1395-300.jpg",
  "episodes": [
    {
      "number": 10,
      "season": 4,
      "title": "The Children",
      "overview": "Circumstances change after an unexpected arrival from north of the Wall. Daenerys must face harsh realities. Bran learns more about his destiny. Tyrion sees the truth about his situation.",
      "screen": "http://slurm.trakt.us/images/episodes/1395-4-10.80.jpg"
    }
  ]
}
MX D
  • 2,453
  • 4
  • 35
  • 47
  • Have a look at this https://github.com/louischatriot/nedb/issues/229 – GPrathap Jan 15 '15 at 02:03
  • @user1574779 I appreciate you trying to help (after 3 months of total silence in this question I even forgot it was here haha), but I'm not using positional operators in my code. I believe it's a bug, but I'm afraid I can't check because I stopped developing the app referent to this question and there is probably a new version of NeDB by now. And looking at the code again, it's probably the "upsert" that's causing the problem, I'm not sure if I checked that. – Carlos Fernandes Jan 16 '15 at 02:36

1 Answers1

0

I had the same issue when I was trying to update an object with no field names that begin with $. I solved this by copying the object to update using angular.copy.

db.update(query, { $addToSet: { episodes: angular.copy(data.episodes[0]) } }, { upsert: true }, function(err, numReplaced, upsert) { ... });

angular.copy creates a deep copy of an object or an array.

Other frameworks and libraries have similar methods (example).

cespon
  • 5,630
  • 7
  • 33
  • 47