node.js - Mongoose:为值 "[ 5ac5cfb41fca8a22f519cb22 ]"转换为数组失败

标签 node.js mongoose casting objectid

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

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 ]

Mongoose :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}]
});

关于node.js - Mongoose:为值 "[ 5ac5cfb41fca8a22f519cb22 ]"转换为数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49691308/

相关文章:

javascript - node.js 无法获取/socket.io

javascript - 如何从expressjs获取表单内选定的单选按钮值?

ios - 将 UIBarButtonItem 转换为 UIButton

node.js - Mongoose /keystonejs : unique field except if field is empty

javascript - Mongodb find() 只包含非空数组

java - 为什么要先转换为 Closeable?

generics - 如何检查该对象是 Haxe 中泛型的实例

node.js - Sinon 在 NodeJS Controller 中模拟 Promise.all

javascript - nodejs 的 express 和 socketio 之间的区别

node.js - Mongoose .js : isModified flag for attribute with default value