0

I have a Mongoose schema that looks like:

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'
        }
    }
});

And I'm trying to update the document with a Match via Express. On a POST request to :matchNumber/:alliance/:seed/:teamNumber/match, I do the following:

import * as flatten from 'flat';

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

When I make the POST request, I get the following error:

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

I should mention I am using TypeScirpt and this was semi working before but I was encountering the issues mentioned here, whose solution caused what I am now experiencing.

Jim
  • 143
  • 3
  • 11

1 Answers1

0

Managed to fix it by removing the flat package and changing it to the following:

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