0

I'm trying to update a database in mongo using a string variable passed in. However, Javascript automatically coerces the variable type, and makes a "type" key in the database instead of what the string type points to is (let's say "notify" for instance)

"update_notifications": function (id ,type ,callback) {
  db.collection("backend_users", function(err, collection) {
    collection.update(
      {"_id": new mongodb.ObjectID(id)},
      { $bit: { type : { xor: 1 } } },
      function (err) {
        if (err) { console.log(color.red(err)); }
        callback(err);
      }
    );
  });
},

Is there anyway to force mongo to use "notify" instead of creating a new "type" key? Thanks!

svoges
  • 9
  • 1
  • Your `type` variable is on the "left" or "key" side of the object notation, so it must be a string which is valid for the "key". This is also how MongoDB works by assigning a value to a "key". Which field in your data are you trying to update actually? It just sounds like you need to wrap `type` with `parseInt`. – Neil Lunn Jun 18 '14 at 00:43
  • The field I'm updating is "notify", and type is being passed in as "notify" as well. When I literally change type to "notify" on the 6th line the code runs. – svoges Jun 18 '14 at 00:45

1 Answers1

0

You basically want to construct your "update" object outside of the statement like this

"update_notifications": function (id ,type ,callback) {
    var update = { "$bit": { } };
    update["$bit"][type] = { xor: 1 };

  db.collection("backend_users", function(err, collection) {
    collection.update(
      {"_id": new mongodb.ObjectID(id)},
      update,
      function (err) {
        if (err) { console.log(color.red(err)); }
        callback(err);
      }
    );
  });
},

The "left" side is always considered a string literal in object notation, but you can assign in the manner that is shown

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317