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

Discord机器人Join DM命令报错schema.findOne不是函数如何解决?

问题原因与修复方案

TypeError: schema.findOne is not a function报错的核心原因是你引入的schema不是Mongoose编译后的模型实例,而是原始的Schema结构。只有通过mongoose.model()编译后的模型才具备findOne、findOneAndDelete等数据库操作方法。


第一步:修复模型导出逻辑

检查你的../../models/joindmmodel.js文件,确保末尾导出的是编译后的模型,正确写法参考:

const mongoose = require('mongoose');

// 定义Schema结构
const joindmSchema = new mongoose.Schema({
  guildId: { type: String, required: true, unique: true },
  Message: { type: String, required: true }
});

// 必须导出编译后的model,不能只导出schema
module.exports = mongoose.model('JoinDM', joindmSchema);

绝大多数新手触发这个报错都是因为错误写成了module.exports = joindmSchema。


第二步:补全缺失的内容保存逻辑

你当前的message子命令仅返回成功提示,没有把用户输入的私信内容写入数据库,修改对应代码段:

if (sub === 'message') {
  const msg = args.slice(1).join(" ")
  const state = new Discord.MessageEmbed()
    .setDescription(`${warn} ${message.author}: You need to provide a **join message**`)
    .setColor(`#efa23a`)
  if (!msg) return message.channel.send(state)
  
  // 新增写入数据库逻辑,upsert参数表示不存在则新建、存在则更新
  await schema.findOneAndUpdate(
    { guildId: message.guild.id },
    { Message: msg },
    { upsert: true, new: true }
  );
  
  return message.channel.send({ embed: { color: "a3eb7b", description: `${approve} ${message.author}: Successfully set your **joindm message**` } })
}

第三步:统一异步写法消除Promise报错

你当前混用了回调函数和async/await语法,容易触发未处理的Promise rejection警告,将clear、test子命令统一改为async/await写法:

clear子命令修改后:

if (sub === 'clear') {
  const data = await schema.findOne({ guildId: message.guild.id });
  if (!data) {
    return message.channel.send({ embed: { color: "#efa23a", description: `${warn} ${message.author}: There is no **joindm message** set for me to clear this` } })
  }
  await schema.findOneAndDelete({ guildId: message.guild.id });
  return message.channel.send({ embed: { color: "#a3eb7b", description: `${approve} ${message.author}: Successfully cleared the **joindm message**` } })
}

test子命令修改后:

if (sub === 'test') {
  const data = await schema.findOne({ guildId: message.guild.id });
  if (!data) {
    return message.channel.send({ embed: { color: "#efa23a", description: `${warn} ${message.author}: There is no **joindm message** set for me to test this` } })
  }
  message.channel.send(data.Message)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:15:03