Search code examples
mongodbexpressmongooseinsert-update

Mongoose express server throws, Cast to string failed for value, error when I try to update a db entry


I have this mongoose express function:

exports.updateSingleAddress = (req, res) => {
  let keyPassed = req.body.key;
  let addressPassed = req.body.address;
  if (!keyPassed) {
    keyPassed = 'nothing here'
  }
  var myquery = { key: { key: keyPassed } };
  var newvalues = { $set: { address: addressPassed } };
  Address.updateOne(myquery, newvalues)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving address."
      });
    }
  );
}

But when I call it with a proper key and address value, I get this:
enter image description here

The model looks like this address.model.js:

module.exports = mongoose => {
    var schema = mongoose.Schema(
      {
        email: String,
        key: String,
        wallet_address: String
      },
      /* { timestamps: false } */
    );
  
    schema.method("toJSON", function() {
      const { __v, _id, ...object } = this.toObject();
      object.id = _id;
      return object;
    });
  
    const Address = mongoose.model("addresses", schema);
    return Address;
};

So why am I getting "message": "Cast to string failed for value "{... and how to I fix this?


Solution

  • On this line:

    var myquery = { key: { key: keyPassed } };
    

    You're passing an object to key. This object also has a field of key with a value of keyPassed. You should directly pass the value of keyPassed.

    var myquery = { key: keyPassed };