Nevada
Nevada

Reputation: 71

TypeError: Cannot read properties of undefined (reading 'findOne')" when using Mongoose in Discord bot

I am building a Discord bot using Discord.js and Mongoose. I have a User model in my MongoDB database and I'm trying to use the findOne method to find a user by their Discord ID. However, when I run my bot, I get the following error:

TypeError: Cannot read properties of undefined (reading 'findOne')

Here's the relevant code:

const User = require('./models/User');

client.on('messageCreate', async (msg) => {
  if (msg.content === '!myinfo') {
    const discordId = msg.author.id;

    const user = await User.findOne({ discordId });

    if (!user) {
      msg.channel.send('You are not registered');
      return;
    }

    msg.channel.send(`Your username is: ${user.username}`);
  }
});

I have checked that my Mongoose connection is working properly and that the User model is correctly defined. What could be causing this error and how can I fix it?

Here is my User model

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  discordId: {
    type: String,
    required: true,
    unique: true,
  },
});

module.exports = mongoose.model('User', userSchema);

Upvotes: 0

Views: 77

Answers (1)

Nabende
Nabende

Reputation: 61

In most cases you have an index.js file that exports all these models. If you have one on the modules folder(where you defined the schema), add the line

export { default as User } from "./User"

You can also add a default export in your schema by changing to look as below

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
  },
  discordId: {
    type: String,
    required: true,
    unique: true,
  },
});
const User = mongoose.model("User", userSchema);

export default User;

Now you can access your schema by the import

import User from "./modules";

Does this help?

Upvotes: 0

Related Questions