我有一个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,其问题导致了我现在遇到的问题。
答案 0 :(得分:0)
设法通过移除扁平包装并将其更改为以下内容来对其进行修复:
const loc = `${alliance}.${seed}`;
const game = await Game.findOneAndUpdate(
{ matchNumber },
{ $set: { [loc]: match._id } },
{ new: true }
);