MissingSchemaError: Schema hasn't been registered for model "undefined".
Use mongoose.model(name, schema)
at Mongoose.model (C:\Users\Brody Hedges\Desktop\DOC Utility\node_modules\mongoose\lib\index.js:551:13)
at Object. (C:\Users\Brody Hedges\Desktop\DOC Utility\src\Schemas.js\stickySchema.js:12:18)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Module._load (node:internal/modules/cjs/loader:930:12)
at Module.require (node:internal/modules/cjs/loader:1113:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object. (C:\Users\Brody Hedges\Desktop\DOC Utility\src\commands\tools\stick.js:3:22)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
DOC Utility\src\Schemas.js\stickySchema.js
const { model, Schema } = require("mongoose");
let stickySchema = new Schema({
Message: { type: String },
ChannelID: { type: String },
LastMessage: { type: String },
LastMessageID: { type: String },
MaxCount: { type: Number, default: 6 },
CurrentCount: { type: Number, default: 0 }
})
module.exports = model("stickSchema". stickySchema);
DOC Utility\src\commands\tools\stick.js
const mongoose = require(`mongoose`);
const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, messageLink } = require('discord.js');
const stickySchema = require('../../Schemas.js/stickySchema');
module.exports = {
data: new SlashCommandBuilder()
.setName("stick")
.setDescription("Makes a sticky message.")
.addStringOption(option => option.setName('message').setDescription('The message you want to stick in chat.').setRequired(true))
.addNumberOption(option => option.setName('count').setDescription('How frequently you want the sticky message to be sent.').setRequired(false))
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
.setDMPermission(false),
async execute(interaction) {
let string = interaction.otpions.getString('message');
let amount = interaction.otpions.getNumber('count') || 6;
const embed = new EmbedBuilder()
.setColor("Blue")
.setDescription(string)
.setFooter({ text: "This is a sticky message"} )
stickySchema.findOne({ ChannelID: interaction.channel.ID}, async (err, data) => {
if (err) throw err;
if (!data) {
let msg = await interaction.channel.send({ embeds: [embed] });
stickySchema.create({
ChannelID: interaction.channel.id,
Message: string,
MaxCount: amount,
LastMessageID: msg.id,
})
return await interaction.reply({ content: "The sticky message has been setup", ephemeral: true});
} else {
await interaction.reply({ content: "You already have a sticky message setup within this channel.", ephemeral: true})
}
})
}
}
Ignore how shitty my code is, I just got back into doing JavaScript. Anyway, if you need any other code please DM me.
Related
hi guys i have an error when i try to send array of string with Mongoose Schema
//Mongoose Schema
const mongoose = require('mongoose');
const { Schema } = mongoose;
const NotesSchema = new Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true,
},
tag: {
type: String,
default: "General"
},
date: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('notes', NotesSchema);
AddNote.js
import React, { useContext, useState } from 'react';
import noteContext from '../context/notes/noteContext';
const AddNote = () => {
const context = useContext(noteContext);
const {addNote } = context;
const [note, setNote] = useState({title: "", description: "", tag: ""})
const handleClick = (e)=>{
e.preventDefault();
addNote(note.title, note.description, note.tag);
setNote({title: "", description: "", tag: ""});
}
const onChange = (e)=>{
setNote({...note, [e.target.name]: [e.target.value]})
}
NoteState.js
const addNote = async (title, description, tag) => {
//API Call
const response = await fetch(`${host}/api/notes/addnote`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'auth-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjM3MTRhYmFlZjgzNDIyOWY5YjE3YzllIn0sImlhdCI6MTY2ODM2OTE0Mn0.uYT7hxbKNRzsuJjMNpuLozIDcAFnvLFQMxykOnzHQ-s'
},
body: JSON.stringify({title, description, tag})
});
const json = await response.json();
console.log(json);
console.log("Adding a new node");
const note = {
"_id": "63754143ce60e68405f291e3",
"user": "63714abaef834229f9b17c9e",
"title": title,
"description": description,
"tag": tag,
"date": "2022-11-16T19:35:47.035Z",
"__v": 0
};
setNotes(notes.concat(note))
}
when i try to addNote i got an error for notes validation failed: title: Cast to string failed for value "[ 'sddgfgg' ]" (type Array) at path "title", description: Cast to string failed for value "[ 'dgfgdgd' ]" (type Array) at path "description", tag: Cast to string failed for value "[ 'fdgfg' ]" (type Array) at path "tag"
notes.js
const express = require('express');
const router = express.Router();
const Note = require('../models/Note');
const fetchuser = require('../middleware/fetchuser');
const { body, validationResult } = require('express-validator');
// Route 1: get all the nots using: GET "/api/notes/fetchallnotes" Login required
router.get('/fetchallnotes', fetchuser, async (req, res) => {
try {
const notes = await Note.find({ user: req.user.id });
res.json(notes)
} catch (error) {
console.error(error.message)
res.status(500).send("Internal server error occured");
}
})
// Route 2: Add a new notes using: POST "/api/notes/addnote" Login required
router.post('/addnote', fetchuser, [
body('title', 'Enter a avalid tilte').isLength({ min: 3 }),
body('description', 'Description must be atleast 5 character').isLength({ min: 5 }),], async (req, res) => {
try {
const { title, description, tag } = req.body;
// if there are errors , return bad request and the errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const note = new Note({
title, description, tag, user: req.user.id
})
const saveNotes = await note.save()
res.json(saveNotes)
} catch (error) {
console.error(error.message)
res.status(500).send("Internal server error occurred");
}
})
[Shopify Sales Tracker/16:28:9]: [ERROR] ➜ uncaughtException => DiscordAPIError: Invalid Form Body
parent_id: Value "" is not snowflake.
at RequestHandler.execute (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async TextChannel.edit (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\structures\GuildChannel.js:336:21)
at async Object.module.exports.run (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\src\client\commands\shopify\addshop.js:16:4)
at async Object.module.exports.run (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\src\client\events\messageCreate.js:29:3)
module.exports.run = async (app, client, message, args) => {
const shop_url = args[0];
if (!app.shopify.config.shops.includes(shop_url)) {
const server = message.guild;
var webhook;
if (!app.shopify.config.webhooks[shop_url]) {
const channel_name = app.config.discord.shop_channel_name(shop_url);
const channel = await server.channels.create(channel_name, {
type: 'text',
});
await channel.setParent(app.config.discord.products_category);
webhook = await channel.createWebhook(shop_url);
}
await app.utils.shopify.addNewShopToConfig(
shop_url,
webhook ? webhook.url : undefined
);
const embed = app.utils.discord.createEmbed('info', {
title: `Shop hinzugefügt [${shop_url}]`,
description: `\`\`${shop_url}\`\` wurde erfolgreich zur Datenbank hinzugefügt.`,
});
await app.utils.shopify.loadProducts();
return await message.channel.send({ embeds: [embed] });
} else {
const embed = app.utils.discord.createEmbed('error', {
description: 'Du hast diesen Shop bereits hinzugefügt',
});
return await message.channel.send({ embeds: [embed] });
}
};
module.exports.conf = {
name: 'addshop',
description: 'Füge einen Shop in die db hinzu',
category: 'Shopify',
owner: false,
premium: false,
admin: false,
guild: true,
dm: false,
disabled: false,
usage: ['addshop <url>'],
example: ['addshop hoopsport.de'],
aliases: ["add"],
minArgs: 0,
maxArgs: 0,
};
The problem is here
await channel.setParent(app.config.discord.products_category);
I see you use this github repo. So look what's on the src folder, config subfolder and discord.js file :
products_category: '', // create a category in your server and put its id inside here
Just create a category channel and copy it's id and paste it here and restart your bot.
So basically I was updating this bot to Discord.js v13 a few months ago and now that I got back to this (I got busy with other things), I can't seem to figure out what went wrong with this Kick command.
The Error
ReferenceError: member is not defined
at Object.run (C:\Users\Admin\OneDrive\Desktop\mybots\testbot\src\Commands\Moderation\Kick.js:49:30)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async run (C:\Users\Admin\OneDrive\Desktop\mybots\testbot\src\Events\InteractionCreate.js:32:11)
kick.js | The kick command src
const { confirm } = require('../../Structures/Utils');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'kick',
description: 'Kick a member.',
category: 'Moderation',
options: [
{
name: 'user',
description: 'Mention a user',
required: true,
type: 'USER'
},
{
name: 'reason',
description: 'Specify reason for kick',
required: true,
type: 'STRING'
}
],
permissions: 'KICK_MEMBERS',
async run({ interaction, bot }) {
const user = interaction.options.getMember('user');
const reason = interaction.options.getString('reason');
if (!user.kickable)
return interaction.reply({
embeds: [new MessageEmbed().setColor('RED').setDescription(`I don't have permissions to kick ${user}.`)]
});
if (user.id === interaction.user.id)
return interaction.reply({
embeds: [new MessageEmbed().setColor('RED').setDescription(`You cannot kick yourself.`)]
});
const confirmation = await confirm(
interaction,
new MessageEmbed()
.setTitle('Pending Conformation')
.setColor('ORANGE')
.setDescription(`Are you sure you want to kick ${user} for reason: \`${reason}\`?`)
.setFooter({ text: 'You have 60 seconds.' })
);
if (confirmation.proceed) {
const embed = new MessageEmbed()
.setColor('ORANGE')
.setDescription(`**${member.user.tag}** was kicked for \`${reason}\`.`);
try {
await user.send({
embeds: [
new MessageEmbed()
.setTitle('You were kicked')
.setColor('ORANGE')
.addField('Reason', reason, false)
.addField('Guild', interaction.guild.name, false)
.addField('Date', time(new Date(), 'F'), false)
]
});
} catch (err) {
embed.setFooter({
text: `I was not able to DM inform them`
});
}
await confirmation.i.update({
embeds: [embed],
components: []
});
await user.kick({ reason });
}
const embed = new MessageEmbed()
.setTitle('Process Cancelled')
.setColor('ORANGE')
.setDescription(`${user} was not kicked.`);
if (confirmation.reason) embed.setFooter({ text: confirmation.reason });
await confirmation.i.update({
embeds: [embed],
components: []
});
}
};
InteractionCreate.js | Another file that showed up in the error
const { MessageEmbed } = require('discord.js');
module.exports = {
event: 'interactionCreate',
async run(bot, interaction) {
if (!interaction.isCommand()) return;
const command = bot.commands.get(interaction.commandName);
if (!command) return;
if (command.permission && !interaction.member.permissions.has(command.permission)) {
return await interaction.reply({
embeds: [
new MessageEmbed()
.setColor('RED')
.setDescription(`You require the \`${command.permission}\` to run this command.`)
]
});
} else {
// If command's category is `NSFW` and if interaction.channel.nsfw is false, inform them to use the command in nsfw enabled channel.
if (command.category === 'NSFW' && !interaction.channel.nsfw) {
await interaction[interaction.deferred ? 'editReply' : interaction.replied ? 'followUp' : 'reply']({
embeds: [
new MessageEmbed()
.setColor('RED')
.setDescription('You can use this command in Age-Restricted/NSFW enabled channels only.')
.setImage('https://i.imgur.com/oe4iK5i.gif')
],
ephemeral: true
});
} else {
try {
await command.run({ interaction, bot, options: interaction.options, guild: interaction.guild });
} catch (err) {
console.log(err);
await interaction[interaction.deferred ? 'editReply' : interaction.replied ? 'followUp' : 'reply']({
embeds: [new MessageEmbed().setColor('RED').setDescription(err.message || 'Unexpected error')]
});
}
}
}
}
};
Thanks a lot in advance!
In line 49 of your Kick.js file you're using member.user.tag but you did not define member. Add this:
const user = interaction.options.getMember('user');
const member = interaction.guild.members.cache.get(user.id);
And in line 72, you're trying to ban the user instead of the guild member.
Change this:
await user.kick({ reason });
To this:
await member.kick({ reason });
I am currently having a problem about my signup command and when searched about the error I am having which is:
MongoServerError: E11000 duplicate key error collection: ShinDB.users index: username_1 dup key: { username: "Shin" }
they always say to drop the collection which I don't want.
what i want is for example i wrote '>signup Shin thisisatest#1234' and if the 'Shin' username is already in the username database it will NOT send the 'MongoServerError' in the console but instead it will send an error 'That username already exist' in the channel which the user send it to.
Signup Command:
var strongRegex = new RegExp("^(?=.{14,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{10,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{8,}).*", "g");
var specialChar = /[`!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
const User = require('../../Database/models/user')
module.exports = {
name: "signup",
description: "Signup for an Economy Account",
usage: ">signup",
aliases: [],
run: async (client, message, args) => {
//message is inguild
if (message.inGuild()) {
return message.reply({ content: `This command can only be used in <#${client.user.id}> DM.\n\`\`Usage: >signup <username> <password>\`\`\n\`\`Note: Your Economy Account is Safe\`\`` })
}
//message is in DM
if (message.channel.type === 'DM') {
// USERNAME
const userargs = args[0]
const pass = args[1]
if (!userargs) {
return message.reply({ content: '**Please provide a username for your Economy Account!\n``Correct Usage: >signup <username> <password>``**' })
}
const userToLow = userargs.toLowerCase()
const user = userToLow.charAt(0).toUpperCase() + userToLow.substring(1, userToLow.length)
if (user.length < 3) return message.reply({ content: '**[__Too Short__]** **Your Username must have atleast 3 Characters**' })
if (user.length > 7) return message.reply({ content: '**[__Too Long__]** **You Username must only have 7 Characters**' })
if (specialChar.test(user)) {
return message.reply({ content: '**Username\'s must not have any Special Characters**' })
}
// PASSWORD
let str
let med
let weak
if (strongRegex.test(pass)) {
str = 'Strong'
}
if (mediumRegex.test(pass)) {
med = 'Medium'
}
if (!strongRegex.test(pass) && !mediumRegex.test(pass)) {
weak = 'Weak'
}
if (!pass) return message.reply({ content: '**Please provide a password for your Economy Account!**' })
if (pass.length < 8) return message.reply({ content: '**[__Too Short__]** **Your Password must have atleast 8 Characters**' })
// CREATING THE ACCOUNT
User.findOne({ createdBy: message.author.id }, async (err, data) => {
if (data) {
return message.reply({ content: `**You already have made an Account and the Username of the Account that you made is: \`\`${data.username}\`\`\n\`\`Note: if you forget your password you can just run the command >recoveraccount\`\`**` })
} else if (err) {
return message.reply({ content: 'That username already exist' })
} else {
new User({
loggedInOn: "0",
createdBy: message.author.id,
isLoggedIn: false,
username: user,
password: pass,
}).save()
return message.reply({ content: 'You have successfuly made an Economy Account!'})
}
})
}
}
}
User Schema/Model:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
loggedInOn: String,
createdBy: String,
isLoggedIn: Boolean,
username: {
type: String,
unique: true
},
password: String
})
module.exports = mongoose.model('Users', userSchema)
Full Error:
return callback(new error_1.MongoServerError(res.writeErrors[0]));
^
MongoServerError: E11000 duplicate key error collection: ShinDB.users index: username_1 dup key: { username: "Shin" }
at C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\operations\insert.js:53:33
at C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection_pool.js:273:25
at handleOperationResult (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\sdam\server.js:327:20)
at Connection.onMessage (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:215:9)
at MessageStream.<anonymous> (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:63:60)
at MessageStream.emit (node:events:527:28)
at processIncomingData (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (C:\Users\Lenovo\Desktop\Shinomy\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10) {
index: 0,
code: 11000,
keyPattern: { username: 1 },
keyValue: { username: 'Shin' },
[Symbol(errorLabels)]: Set(0) {}
}
My Database Current Collections:
Collections Picture
i hope i have explained it very well, any help would be really appreciated. thanks.
To fix your bot instance shutting down use the following:
client.on('error', (error) => {
console.error(error)
// You can also put your "error message" create here
})
Along with that. Whatever you're doing with your MongoDB code is very "jank". The following will likely fix it.
User.findOne({ createdBy: message.author.id }).then((data) => {
if (data) {
return message.reply({
content: `**You already have made an Account and the Username of the Account that you made is: \`\`${data.username}\`\`\n\`\`Note: if you forget your password you can just run the command >recoveraccount\`\`**`,
});
} else if (!data) {
User.findOne({ username: user }).then((findUsername) => {
if (findUsername) {
return message.reply('There is already an account with that username!')
} else {
new User({
loggedInOn: '0',
createdBy: message.author.id,
isLoggedIn: false,
username: user,
password: pass,
}).save();
return message.reply({ content: 'You have successfuly made an Economy Account!' });
}
});
}
});
Let me know if you have any questions
I'm learning Node.js and trying to build a simple application for movie rentals service. This is my code for defining schema for movies and it's throwing an error.
const Joi = require('joi');
const mongoose = require('mongoose');
const {genreSchema} = require('./genre');
//the below line thorws error and terminal points cursor at "new"
const Movie = mongoose.model('Movies',new mongoose.Schema({
type: String,
required: true,
trim: true,
minlength: 5,
maxlength: 255
},
genre: {
type: genreSchema,
required: true
},
numberInStock: {
type: Number,
required: true,
min: 0,
max: 255
},
dailyRentalRate: {
type: Number,
required: true,
min: 0,
max: 255
}
}));
function validateMovie(movie) {
const schema = {
title: Joi.string().min(5).max(50).required(),
genreId: Joi.objectId().required(),
numberInStock: Joi.number().min(0).required(),
dailyRentalRate: Joi.number().min(0).required()
};
return Joi.validate(movie, schema);
}
exports.Movie = Movie;
exports.validate = validateMovie;
This is the ./genre. Please check it.
const mongoose = require('mongoose');
const Joi = require('joi');
const genreSchema = new mongoose.Schema({
name:{
type:String,
required:true,
minlength: 5,
maxlength: 50
}
})
const Genre = mongoose.model('Genre', genreSchema);
function validateGenre(genre){
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(genre,schema);
}
exports.Genre=Genre;
exports.validate = validateGenre;
This is ./rentals file. It is also throwing `Object.anonymous' error.
const { Rental, validate } = require('../models/rental');
const { Movie } = require('../models/movie');
const { Customer } = require('../models/customer');
const auth = require('../middleware/auth');
const mongoose = require('mongoose');
const Fawn = require('fawn');
const express = require('express');
const router = express.Router();
Fawn.init(mongoose);
router.get('/', auth, async (req, res) => {
const rentals = await Rental.find()
.select('-__v')
.sort('-dateOut');
res.send(rentals);
});
router.post('/', auth, async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const customer = await Customer.findById(req.body.customerId);
if (!customer) return res.status(400).send('Invalid customer.');
const movie = await Movie.findById(req.body.movieId);
if (!movie) return res.status(400).send('Invalid movie.');
if (movie.numberInStock === 0)
return res.status(400).send('Movie not in stock.');
let rental = new Rental({
customer: {
_id: customer._id,
name: customer.name,
phone: customer.phone
},
movie: {
_id: movie._id,
title: movie.title,
dailyRentalRate: movie.dailyRentalRate
}
});
try {
new Fawn.Task()
.save('rentals', rental)
.update('movies',{ _id: movie._id },{
$inc: { numberInStock: -1 }
})
.run();
res.send(rental);
}
catch (ex) {
res.status(500).send('Something failed.');
}
});
router.get('/:id', [auth], async (req, res) => {
const rental = await Rental.findById(req.params.id).select('-__v');
if (!rental)
return res.status(404).send('The rental with the given ID was not found.');
res.send(rental);
});
module.exports = router;
This is the error message I'm getting. I'm on Windows and my text editor is VScode and terminal is powershell
PS D:\Study\Vidly> node index.js
D:\Study\Vidly\node_modules\mongoose\lib\schema.js:475
throw new TypeError('Invalid value for schema path `' + fullPath +
^
TypeError: Invalid value for schema path `genre.type`, got value "undefined"
at Schema.add (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:475:13)
at Schema.add (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:509:12)
at new Schema (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:129:10)
at Object.<anonymous> (D:\Study\Vidly\models\movie.js:5:39)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (D:\Study\Vidly\routes\rentals.js:2:19)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
Based on your genre.js file, you need to change this
const {genreSchema} = require('./genre');
to
const {Genre} = require('./genre');
And this:
...
genre: {
type: genreSchema,
required: true
},
...
to
genre: {
type: Genre,
required: true
},
you need to export the genreSchema from the genre file also.
exports.Genre=Genre
exports.validate=validateGenre
exports.genreSchema=genreSchema