UnhandledPromiseRejectionWarning:CastError:猫鼬中的值转换为字符串失败

时间:2020-09-21 12:53:16

标签: node.js mongoose

我已经实现了一种使用nodejs从mongodb检索一些数据的方法。一旦执行了该方法,它将在控制台中给我以下错误

(node:7960) UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{
  Unavailable: [
    { day: 'Monday', startTime: '10:30', endTime: '12.30' },
    { day: 'Tuesday', startTime: '11:00', endTime: '12.00' }
  ],
  _id: 5f2822f522dec4051444bf2c,
  building: 'Computing',
  room: 'A-301',
  capacity: 250,
  type: 'Lecture hall',
  __v: 0
}" at path "room" for model "Room"
    at model.Query.exec (/Users/applefactory/IdeaProjects/time_table_generation_chernobyl/backend/node_modules/mongoose/lib/query.js:4351:21)
    at model.Query.Query.then (/Users/applefactory/IdeaProjects/time_table_generation_chernobyl/backend/node_modules/mongoose/lib/query.js:4443:15)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:7960) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7960) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

方法的实现:

async function getRoomDetails(_room){

    let preferredRoomDetails="";
// console.log('Start')
    preferredRoomDetails = await Rooms.findOne({room : _room});
// console.log("End")
    console.log(preferredRoomDetails)
    return preferredRoomDetails;
}

(通过使用控制台日志,我能够找到发生错误并在上述方法中发生错误的确切位置)

房间模型类:

const mongoose = require('mongoose');

const schema = mongoose.Schema;

const RoomSchema = new schema({
    building : {
        type: String,
        required: true,
        unique:true,
    },
    room:{
        type: String,
        required: true,
        unique:true
    },
    capacity:{
        type: Number,
        required: true,
        unique:true
    },
    type:{
        type: String,
        required: true,
        unique:true
    },
    Unavailable:{
        type:Array
    }
});

const Room= mongoose.model('Room',RoomSchema);

module.exports = Room;

如何解决此问题?谢谢您的时间!

1 个答案:

答案 0 :(得分:1)

也许可以检查函数“ getRoomDetails”的“ _room”参数:

async function getRoomDetails(_room)

您似乎正在传递对象?如果是这样,您可能想更改

    preferredRoomDetails = await Rooms.findOne({room : _room});

    preferredRoomDetails = await Rooms.findOne({room : _room._id});