Search code examples
node.jsmongodbexpressmongoose

Error using mongoose: TypeError: Invalid schema configuration: `Model` is not a valid type at path


My Role.js looks like this:

const mongoose = require ("mongoose");

const roleSchema = mongoose.Schema({
    role : Number,
    description : String            
});

module.exports = mongoose.model("Role", roleSchema);

In my logic.js, I am trying to do this:

const Role = require('./Collections/Role');
const role = Role.create({
        role: 2,
        description: 'Editor'
    })    
    console.log(role);

I can't seem to get it right. I found a couple other threads with almost similar problem, but it didn't help me.

I also tried

const Schema = mongoose.Schema;
const roleSchema = new Schema({ ...
...
const Role = mongoose.model("Role", roleSchema);
module.exports = Role;

The error

C:\Users\my_is\Programming\Project\node_modules\mongoose\lib\schema.js:1340
    throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
    ^    
TypeError: Invalid schema configuration: `Model` is not a valid type at path `role`. See 
    at Schema.interpretAsType 
    at Schema.path 
    at Object.<anonymous> (C:\Users\my\Programming\Project\Collections\Admin.js:6:30)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)

------------------ My Admin.js --------------

const mongoose = require ("mongoose");
const Role = require("./Role");
//const Role = require("./Role").schema;  

const adminSchema = mongoose.Schema({
    firstName : String,    
    lasteName : String,
    email : String,
    dateCreate : { type: Date, default : Date.now } ,
    role : Role
})

module.exports = mongoose.model("Admin", adminSchema);

Solution

  • I noticed you include the entire Role model in the adminSchema rather than just the schema. to fix this change the line role: Role into type: mongoose.Schema.Types.ObjectId and set the reference to the role. here is a example

    const adminSchema = mongoose.Schema({
        firstName : String,    
        lasteName : String,
        email : String,
        dateCreate : { type: Date, default : Date.now },
        role : { type: mongoose.Schema.Types.ObjectId, ref: "Role" }
    })
    

    hope this will work :)