user13716236
user13716236

Reputation:

Facing "throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +"

Working into NodeJS with Typescript. So the major issue is I am trying to follow the One-To-Many Document structure using Mongoose. But as the question says, I face the issue:

throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +

TypeError: Invalid schema configuration: `Todo` is not a valid type at path `ref`

Here is the Model Code:


const Schema = mongoose.Schema;
const userSchema = new Schema({
    _id: Schema.Types.ObjectId,
    firstname: {
        type: String
    },
    lastName: {
        type: String,
    },
    email: {
        type: String,
        required: "Enter Email ID"
    },
    password: {
        type: String,
        required: "Enter Password"
    },
    todos: [
        {
            ref: 'Todo',
            _id: Schema.Types.ObjectId
        }
    ]
});

const todoSchema = new Schema({
    _id: Schema.Types.ObjectId,

    title: {
        type: String,
        required: "Enter a title"
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    content: {
        type: String
    }
})

export const Todo = mongoose.model('Todo', todoSchema);
export const User = mongoose.model('User', userSchema);

Upvotes: 1

Views: 2669

Answers (2)

mykoman
mykoman

Reputation: 1905

This is just a more concise solution to Mohammed's solution.

type is the most important object key while defining your schema and it is missing for your todo field. You need to set type to ObjectId like this

const Schema = mongoose.Schema;
const userSchema = new Schema({
    ...
    todos: [
        {
            type: Schema.Types.ObjectId, 
            ref: 'Todo'
        }
    ]
});

Upvotes: 0

Mohammed Yousry
Mohammed Yousry

Reputation: 2184

when you define a reference property in a schema, you just need to define its type and mention it references to which db model

the type should be an objectId

the schema should be something like this

const Schema = mongoose.Schema;
const userSchema = new Schema({
    _id: Schema.Types.ObjectId,
    firstname: {
        type: String
    },
    lastName: {
        type: String,
    },
    email: {
        type: String,
        required: "Enter Email ID"
    },
    password: {
        type: String,
        required: "Enter Password"
    },
    todos: [
        {
            type: Schema.Types.ObjectId, // here is the issue
            ref: 'Todo'
        }
    ]
});

hope it helps

Upvotes: 1

Related Questions