typescript - 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,这之前是半工作的,但我遇到了这里提到的问题,其解决方案导致了我现在遇到的问题。
解决方案
设法通过删除平面包并将其更改为以下内容来修复它:
const loc = `${alliance}.${seed}`;
const game = await Game.findOneAndUpdate(
{ matchNumber },
{ $set: { [loc]: match._id } },
{ new: true }
);
推荐阅读
- java - 尝试使用类路径运行 Java 程序;java 找不到我原来的编译类
- ionic-framework - 使用 Ionic 3 中的相机拍摄的 FTP 上传图像
- typescript - 在 vscode 中快速调试打字稿
- python - Plotting a Function Over Multiple Constants
- javascript - NodeJS:为什么 new Date().toLocaleString() 忽略系统时区?
- java - Error in netbeans when try to run program: Truncated module-info.class
- scala - 如何将 Spark 数据集字段(包装数组)转换为 Spark Java 中的映射或数组列表
- build - Artifactory 可以根据构建时间而不是版本号来保留构建吗?
- javascript - Django 表单不显示日期小部件
- c# - WPF 中的绑定验证