简体   繁体   English

使用导出的 mongoose.model() 时无法读取未定义(创建)的属性

[英]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')使用 discord.js 创建机器人。通过 mongoose 连接到 mongoDB 并尝试添加测试数据时,我遇到了这个错误: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:导出的 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.我尝试了将数据添加到数据库的不同方法,但唯一有效的测试是当我在同一代码块中同时声明 memberSchema 和新成员时。 Any advice to properly import / export the memberSchema model?关于正确导入/导出 memberSchema model 的任何建议?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM