【问题标题】:Mongoose: Cast to ObjectId failed for value "ObjectID" at path "red.s1"Mongoose:路径“red.s1”处的值“ObjectID”转换为 ObjectId 失败
【发布时间】:2020-04-18 16:05:45
【问题描述】:

我有一个看起来像这样的 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 更新文档。在对:matchNumber/:alliance/:seed/:teamNumber/match 的 POST 请求中,我执行以下操作:

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,这之前是半工作的,但我遇到了提到的问题 here,其解决方案导致了我现在遇到的问题。

【问题讨论】:

    标签: typescript express mongoose


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-05-26
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 2013-03-24
      • 2014-06-20
      • 2017-05-19
      相关资源
      最近更新 更多