Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While using an exported mongoose.model() cannot read properties of undefined (create)

Creating a bot with discord.js. While connecting to mongoDB via mongoose and trying to add test data I have run into this error: TypeError: Cannot read properties of undefined (reading ‘create’)

 const {MemberSchema} = require('../schemas/member-schema');

    module.exports = {
      name: 'interactionCreate',
      async execute(interaction) {
        if (!interaction.isButton()) return;
        console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered a button interaction.`);
        const author = await interaction.member.id;
        const guild = await interaction.guildId;
        const points = 100;

        let member = {
          userID: `${guild}`,
          guildID: `${author}`,
          points: points
        }
        try {
          let newMember = await MemberSchema.create(member);
          await newMember.save();
        } catch (e) {
          console.log(`error creating member ${e}`);
        }
      },
    };

The exported MemberSchema:

const mongoose = require('mongoose');

const MemberSchema = new mongoose.Schema({
    userID: mongoose.SchemaTypes.String,
    guildID: mongoose.SchemaTypes.String,
    points: Number
});

module.exports = mongoose.model('Member', MemberSchema);

I’ve tried different methods of adding data to the database but the only test that worked was when I declared both the memberSchema and a new member in the same block of code. Any advice to properly import / export the memberSchema model?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your import statement is incorrect. You should be importing like this

const Member = require('../schemas/member-schema');

Then in route, use

await Member.create(member);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading