You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose/MongoDB子文档数据无法填充问题求助

问题解决

核心问题:字段名大小写不匹配

你的Mongoose Schema中定义的字段是possibleAnswers(驼峰命名,A大写),但在seeds文件中你写成了possibleanswers(全小写),Mongoose对字段名大小写敏感,所以无法正确识别并填充数据。

额外问题:insertMany混用await和回调函数

insertMany支持Promise语法,你已经使用了await,就不要再传入回调函数,否则会导致异步逻辑混乱,建议用try/catch来处理错误。

修正后的seeds文件代码

await Question.deleteMany();

const possibleAnswersData = [{ a: "した", b: "じた", c: "しだ", d: "ちた"}];

try {
  const questions = await Question.insertMany([
    {
      description: "What is the reading of the Kanji below?",
      question: "上",
      possibleAnswers: possibleAnswersData, // 修正字段名大小写
      level: "N5",
      questionType: "kanji",
    }
  ]);
  console.log(questions);
  console.log("questions seeded");
} catch (err) {
  console.log(err);
}

补充说明

  1. 确保possibleAnswersData的结构和possibleAnswersSchema完全匹配,你当前的结构是正确的,每个元素包含a/b/c/d四个必填字符串字段。
  2. 如果是插入单个文档,也可以用Question.create()替代insertMany,代码会更简洁:
const question = await Question.create({
  description: "What is the reading of the Kanji below?",
  question: "上",
  possibleAnswers: possibleAnswersData,
  level: "N5",
  questionType: "kanji",
});

内容的提问来源于stack exchange,提问作者j_art_fox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:40:38