skip to Main Content

I am trying to insert an array to
a schema that holds an array of strings but I get the same error every time:

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

I have tried every option possible for inverting the array of strings / numbers / objectId to the schema from the web with Postman via Visual Studio Code with promise and await the error is as follows:

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"

2

Answers


  1. Chosen as BEST ANSWER

    so it turn out that the version of mongoose that i was using was maybe outdated so after new install it work perfect


  2. The error message points to the fact that the value of the students field is being treated as a string instead of an array of ObjectIds. This could be happening because the students array is not being properly defined as an array in the code. Instead, it is being defined as a string that happens to look like an array.

    To fix this issue, you should ensure that the students field is being properly defined as an array. One way to do this is to modify the students field in your schema definition to include an array type and a default empty array, like this:

    students: {
        type: [mongoose.Schema.Types.ObjectId],
        ref: "student",
        default: [],
    },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search