猫鼬:施放到数组失败的值“[5ac5cfb41fca8a22f519cb22]”

时间:2018-04-06 11:02:41

标签: node.js mongoose casting objectid

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

  

游戏验证失败:rounds.1.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,
  }
});

插入功能:

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 
}

参数round是:

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

console.log(round.questions)结果:

[ 5ac5cfb41fca8a22f519cb22 ]

猫鼬:5.0.12,

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

1 个答案:

答案 0 :(得分:1)

试试这个..

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