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); }
补充说明
- 确保
possibleAnswersData的结构和possibleAnswersSchema完全匹配,你当前的结构是正确的,每个元素包含a/b/c/d四个必填字符串字段。 - 如果是插入单个文档,也可以用
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
相关产品推荐
相关产品推荐

