node.js – Mongoose:转换为数组失败,值为“[5ac5cfb41fca8a22f519cb22]”

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

Game validation failed: rounds.1.questions: Cast to Array failed for value “[ 5ac5cfb41fca8a22f519cb22 ]” at path “questions”

架构的:

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

插入功能:

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()
}

参数游戏是:

{ 
   teams: [],
   rounds: 
    [ { categories: [Array],
        questions: [],
        _id: 5ac7507c5491ed422de3ce68,
        roundNumber: 1 } ],
   _id: 5ac74cccc65aac3e0c4b6cde,
   code: '537epG',
   __v: 1 
}

参数轮是:

{ 
   roundNumber: 1,
   questions: [ '5ac5cfb41fca8a22f519cb22' ],
   categories: [ 'Art and Literature', 'Music', 'Science and Nature' ] 
}

console.log(round.questions)结果:

[ 5ac5cfb41fca8a22f519cb22 ]

猫鼬:5.0.12,

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

最佳答案 试试这个..

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