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

如何使用Mongoose从MongoDB读取指定数据用于Discord机器人回复

问题描述

已将用户数据存储在MongoDB Atlas中,需要实现读取数据并在Discord机器人回复中展示对应用户昵称的功能,现有注册提交代码、数据Schema如下,自行编写的昵称查询代码无法正常运行。

现有数据提交代码

const subregis = "!reg ign:";
client.on("message", msg => {
  if (msg.content.includes(subregis)){ 
      const user = new User({
        _id: mongoose.Types.ObjectId(),
        userID: msg.author.id,
        nickname: msg.content.substring(msg.content.indexOf(":") + 1)
      });
      user.save().then(result => console.log(result)).catch(err => console.log(err));
      msg.reply("Data has been submitted successfully") 
  }
});

现有数据Schema定义

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const profileSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    userID: String,
    nickname: String,
});

module.exports = mongoose.model("User", profileSchema);

无法正常运行的查询代码

client.on("message", msg => {
  if (msg.content === "!nickname"){ 
      msg.reply("Your Nickname:", User.findById(nickname))
  }
});
错误原因
  1. 查询条件错误:findById需要传入MongoDB自动生成的_id值,你存储数据时单独存了Discord用户ID到userID字段,查询当前发令用户的昵称应该匹配userID = msg.author.id,原代码里的nickname变量根本没有定义,查询条件完全不成立
  2. Mongoose数据库操作是异步执行的,原代码直接把查询的Promise对象传给回复方法,拿不到实际查询结果就会发送消息
  3. 缺少异常处理和边界判断,查询出错、用户未注册时程序会直接报错,无任何用户提示
修正后的实现代码

昵称查询功能代码

// 加async关键字支持异步等待
client.on("message", async msg => {
  // 跳过机器人自身发送的消息,避免触发无限回复循环
  if (msg.author.bot) return;
  if (msg.content === "!nickname"){ 
      try {
        // 用当前发送消息的用户ID匹配数据库记录,等待查询返回结果
        const userData = await User.findOne({ userID: msg.author.id });
        if (!userData) {
          return msg.reply("你还未完成注册,请先使用 !reg ign:你的昵称 提交信息");
        }
        msg.reply(`你的昵称是:${userData.nickname}`);
      } catch (err) {
        console.error("查询昵称出错:", err);
        msg.reply("数据查询失败,请稍后重试");
      }
  }
});

注册逻辑优化(可选但建议添加)

原注册逻辑没有做重复校验,同一个用户多次触发指令会生成多条重复数据,优化后代码如下:

const subregis = "!reg ign:";
client.on("message", async msg => {
  if (msg.author.bot) return;
  if (msg.content.includes(subregis)){ 
      try {
        // 先校验用户是否已经注册
        const existUser = await User.findOne({ userID: msg.author.id });
        if (existUser) {
          return msg.reply("你已经提交过注册信息,无需重复操作");
        }
        const inputNickname = msg.content.substring(msg.content.indexOf(":") + 1).trim();
        const user = new User({
          _id: new mongoose.Types.ObjectId(),
          userID: msg.author.id,
          nickname: inputNickname
        });
        await user.save();
        msg.reply("Data has been submitted successfully") 
      } catch (err) {
        console.error("注册提交出错:", err);
        msg.reply("数据提交失败,请稍后重试");
      }
  }
});

注意:确保代码运行前已经完成Mongoose连接MongoDB Atlas的配置,且User模型在事件监听逻辑之前正确引入,否则会触发模型未定义的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 14:54:19