Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: cast to array failed for value "[ 5ac5cfb41fca8a22f519cb22 ]"

I am trying to insert a round in a existing game, which gives me the following error:

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

Schema's:

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

insert function:

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

Parameter game is:

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

Parameter round is:

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

console.log(round.questions) result :

[ 5ac5cfb41fca8a22f519cb22 ]

mongoose : 5.0.12,

I have no idea what i am doing wrong here. And would appreciate some help here.

like image 256
DanieldeJong93 Avatar asked Oct 29 '22 15:10

DanieldeJong93


1 Answers

Try this..

const roundSchema = Schema({
  roundNumber: {
    type: Number,
    required: true,
  },
  categories: {
    type: [String],
    required: true
  },
  questions: [{type: Schema.Types.ObjectId, ref: 'Question', required: true}]
});
like image 115
Igal Klebanov Avatar answered Nov 01 '22 19:11

Igal Klebanov