首页 > 解决方案 > Mongoose:路径“red.s1”处的值“ObjectID”转换为 ObjectId 失败

问题描述

我有一个 Mongoose 模式,如下所示:

const gameSchema = new Schema({
    matchNumber: {
        type: Number,
        required: [true, 'A match must have a number!'],
        unique: true
    },
    red: {
        s1: {
            type: ObjectId,
            ref: 'Match'
        },
        s2: {
            type: ObjectId,
            ref: 'Match'
        },
        s3: {
            type: ObjectId,
            ref: 'Match'
        }
    }
});

我正在尝试通过 Express 使用 Match 更新文档。在 POST 请求中 :matchNumber/:alliance/:seed/:teamNumber/match,我执行以下操作:

import * as flatten from 'flat';

let match = req.body;
const game = await Game.findOneAndUpdate(
    { matchNumber },
    flatten({ [alliance]: { [seed]: match._id } }),
    { new: true }
);

当我发出 POST 请求时,我收到以下错误:

CastError: Cast to ObjectId failed for value "ObjectID" at path "red.s1"

我应该提到我正在使用 TypeScirpt,这之前是半工作的,但我遇到了这里提到的问题,其解决方案导致了我现在遇到的问题。

标签: typescriptexpressmongoose

解决方案


设法通过删除平面包并将其更改为以下内容来修复它:

const loc = `${alliance}.${seed}`;
const game = await Game.findOneAndUpdate(
    { matchNumber },
    { $set: { [loc]: match._id } },
    { new: true }
);

推荐阅读