9.2 Referencing Documents. The course code throws a validation error

When I follow the course code

const Course = mongoose.model('Course', new mongoose.Schema({
  name: String,
  author : {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Author'

I got this error

ValidationError: Course validation failed: author: Cast to ObjectId failed for value "authorId" (type string) at path "author" because of "BSONTypeError"

My mongoose version is 6.8.3. Any help is appreciated!

That is a validation issue:
in your validation logic use something like:

// you have a mongoose object already.
// i.e., const mongoose = require('mongoose');

    // set the validation message here.
    // Note: this logic is by default available in mongoose. But you can use some Joi extension 
    // that can do this for you.

Problem: you probably don’t have a valid authorId and you are passing string OR you have a valid author id but you are not using a proper validator to check it’s type. Meaning, by default your API call POST data will be treated as string values and ObjectId is not a string (ObjectId).

Let us know if it helped or not.

If this doesn’t help, please show us more code.

Thank you for your reply. I found that I forgot to change the ‘authorID’ to the actual ID.

hallo sir. I beginner with mongodb and we have same problem, can you show solve code of you sir?