You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js v14中Sequelize model.create()非函数问题求助

问题排查与解决方案

核心问题定位

model.create() isn't a function 报错的本质是你代码中调用create方法的变量不是有效的Mongoose模型实例,大概率是模型导出/导入环节出了问题。

分步排查修复

1. 检查模型文件的导出逻辑

确保你的用户模型是通过mongoose.model()创建并正确导出的,而非直接导出Schema:

// 正确的模型文件示例(如models/User.js)
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  userId: { type: String, required: true },
  guildId: { type: String, required: true },
  // 其他自定义字段
});

// 必须导出mongoose.model创建的实例
module.exports = mongoose.model('User', userSchema);

如果导出的是userSchema而非模型实例,自然不会有create方法。

2. 确认模型导入方式

在同步命令或数据库工具文件中,检查模型导入是否正确:

// 错误示例:导入了Schema而非模型
const User = require('../models/User').schema;

// 正确示例:直接导入模型实例
const User = require('../models/User');

3. 修正同步成员的逻辑代码

同步成员时,先通过findOne校验条目是否存在,不存在再调用create,同时确保跳过机器人账号:

// 同步命令中的核心逻辑示例
async function syncGuildMembers(guild) {
  const members = await guild.members.fetch();
  for (const [id, member] of members) {
    if (member.user.bot) continue; // 跳过机器人,避免无效条目

    const existingEntry = await User.findOne({
      userId: id,
      guildId: guild.id
    });

    if (!existingEntry) {
      await User.create({
        userId: id,
        guildId: guild.id
        // 其他字段可设置默认值
      });
    }
  }
}

4. 验证数据库连接顺序

在index.js中,必须确保MongoDB连接成功后再加载模型和命令:

const mongoose = require('mongoose');
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers // 必须开启此意图才能获取成员列表
  ]
});

// 先建立数据库连接
mongoose.connect('你的MongoDB连接字符串')
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.error('数据库连接失败:', err));

// 再加载命令、事件等逻辑
// ... 你的其他代码

模型若在数据库连接前加载,可能会初始化失败,导致无法调用模型方法。

额外调试技巧

  • 开启Mongoose调试模式:mongoose.set('debug', true);,可以查看详细的数据库操作日志
  • 打印User变量的类型:console.log(typeof User, User),确认是模型实例而非Schema或其他类型

内容的提问来源于stack exchange,提问作者CrossTR15_YT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:00:00