最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

我无法创建以任何方式保存数组的模式

网站源码admin32浏览0评论

我无法创建以任何方式保存数组的模式

我无法创建以任何方式保存数组的模式

我正在尝试插入一个数组 一个包含字符串数组的模式,但我每次都会遇到同样的错误:

const mongoose = require("mongoose");

const teamSchema = new mongoose.Schema({
  teamName: {
    type: String,
    required: true,
  },
  teamTeacher: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  isActive: {
    type: Boolean,
    default: true,
  },
  students: [{
   type: [mongoose.Schema.Types.ObjectId],
   ref: "student",
  }],
});

const Team = mongoose.model("Team", teamSchema);

const team1 = new Team({
  teamName: "team1",
  students: ["6451fe33cb3ca7242f39d2e7", "6451fe15cb3ca7242f39d2e2"],
  teamTeacher: "6450c60798100f4d0a7cffb3",
});
async function saveD() {
 await team1.save();
}
saveD();
console.log(team1);

我已经尝试了所有可能的选项,通过 Visual Studio Code 使用 Postman 将字符串/数字/objectId 的数组从 Web 反转为模式,并承诺等待错误如下:

this.$__.validationError = new ValidationError(this);
                               ^

ValidationError: Team validation failed: students: Cast to [undefined] failed for value "[]" (type string) at path "students.0" because of "TypeError", students.undefined: Cast to [undefined] failed for value "["6451fe33cb3ca7242f39d2e7","6451fe15cb3ca7242f39d2e2"]" (type string) at path "students.undefined" because of "TypeError"
回答如下:

错误消息指出学生字段的值被视为字符串而不是 ObjectId 数组。发生这种情况的原因可能是学生数组未在代码中正确定义为数组。相反,它被定义为一个看起来像数组的字符串。

要解决此问题,您应该确保学生字段被正确定义为数组。一种方法是修改模式定义中的学生字段以包含数组类型和默认空数组,如下所示:

students: {
    type: [mongoose.Schema.Types.ObjectId],
    ref: "student",
    default: [],
},
发布评论

评论列表(0)

  1. 暂无评论