Mongoose:由于值“[5ac5cfb41fca8a22f519cb22]”而无法转换为数组

Dan*_*g93 5 casting mongoose node.js objectid

我试图在现有游戏中插入一个回合,这给了我以下错误:

游戏验证失败:rounds.1.questions:Cast to Array 在路径“questions”处的值“[ 5ac5cfb41fca8a22f519cb22 ]”失败

架构的:

const roundSchema = Schema({
  roundNumber: {
    type: Number,
    required: true,
  },
  categories: {
    type: [String],
    required: true
  },
  questions: {
    type: [Schema.Types.ObjectID],
    ref: 'Question',
    required: true,
  }
});

const gameSchema = Schema({
  code: {
    type: String,
    required: true,
  },
  teams: {
    type: [Schema.Types.ObjectID],
    required: false,
  },
  rounds: [roundSchema]
});

const questionSchema = Schema({
  question: {
    type: String,
    required: true,
  },
  answer: {
    type: String,
    required: true,
  },
  category: {
    type: String,
    required: true,
  }
});
Run Code Online (Sandbox Code Playgroud)

插入功能:

function createRoundForGame(game, round) {
  round.questions = round.questions.map((question) => {
    return mongoose.Types.ObjectId(question);
  });

  console.log(round.questions);
  game.rounds.push(round);

  return game.save()
}
Run Code Online (Sandbox Code Playgroud)

参数博弈为:

{ 
   teams: [],
   rounds: 
    [ { categories: [Array],
        questions: [],
        _id: 5ac7507c5491ed422de3ce68,
        roundNumber: 1 } ],
   _id: 5ac74cccc65aac3e0c4b6cde,
   code: '537epG',
   __v: 1 
}
Run Code Online (Sandbox Code Playgroud)

参数轮为:

{ 
   roundNumber: 1,
   questions: [ '5ac5cfb41fca8a22f519cb22' ],
   categories: [ 'Art and Literature', 'Music', 'Science and Nature' ] 
}
Run Code Online (Sandbox Code Playgroud)

console.log(round.questions) 结果:

[ 5ac5cfb41fca8a22f519cb22 ]
Run Code Online (Sandbox Code Playgroud)

猫鼬:5.0.12,

我不知道我在这里做错了什么。并希望得到一些帮助。

Iga*_*nov 2

尝试这个..

const roundSchema = Schema({
  roundNumber: {
    type: Number,
    required: true,
  },
  categories: {
    type: [String],
    required: true
  },
  questions: [{type: Schema.Types.ObjectId, ref: 'Question', required: true}]
});
Run Code Online (Sandbox Code Playgroud)