0

获取此 CastError: Cast to ObjectId failed for value "" (type string) at path "_id"for model"State"

const mongoose = require("mongoose");
mongoose.Promise = global.Promise;

const modelSchema = new mongoose.Schema({ name: String });
const modelName = "State";

if (mongoose.connection && mongoose.connection.models[modelName]) {
  module.exports = mongoose.connection.models[modelName];
} else {
  module.exports = mongoose.model(modelName, modelSchema);
}

if (data.state) {
  if (mongoose.Types.ObjectId.isValid(data.state)) {
    const stateCheck = await State.findById(data.state);
    if (!stateCheck) {
      res.json({ error: "State dont exist" });
      return false;
    }
    updates.state = data.state;
  }
}
4

1 回答 1

0

in 的值data.state可能是一个空字符串。

Mongoose 尝试将空字符串转换为 ObjectId 并失败。

于 2021-12-27T18:57:02.867 回答