skip to Main Content

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:Usersmy_isProgrammingProjectnode_modulesmongooselibschema.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:UsersmyProgrammingProjectCollectionsAdmin.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);

2

Answers


  1. you should export roleSchema from role.js to admin.js
    and set role type in admin.js

    roleSchema

    and it will work…

    Login or Signup to reply.
  2. 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 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search