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

xzlaal3s  于 2023-03-23  发布在  Go
关注(0)|答案(1)|浏览(130)

我有一个mongoose express函数:

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."
      });
    }
  );
}

但是当我用一个正确的键和地址值调用它时,我得到了这个:

模型看起来像这样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;
};

为什么我会收到“消息”:“Cast to string failed for value“{... and how to I fix this?

jobtbby3

jobtbby31#

在这一行:

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

您正在向key传递一个对象。该对象也有一个字段key,其值为keyPassed。您应该直接传递keyPassed的值。

var myquery = { key: keyPassed };

相关问题