【问题标题】:Mongoose not saving data according to a function (discord.js)猫鼬不根据函数保存数据(discord.js)
【发布时间】:2022-01-24 20:10:07
【问题描述】:

今天,我决定制作一个 Discord RPG 机器人,它当然需要个人资料统计信息,例如硬币和实际用户。因此,我搜索了tutorial on how I can do this with MongoDB,但遇到了一个问题。当公会成员加入并且机器人正在运行时,数据不会完全没有错误地保存,我不确定为什么会发生这种情况。我尝试通过在机器人尝试连接到数据库后添加一行 console.log(mongoose.connection.readyState) 来解决连接状态问题。这将返回1,表示连接正常。我找不到任何其他原因造成这种情况,所以我决定在思考几个小时后提出一个问题。

(index.js): 连接数据库

const mongoose = require("mongoose");

mongoose.connect(process.env.MONGO_SERVER, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => [
    console.log("Connected to MongoDB Database successfully!"),
    console.log(mongoose.connection.readyState)
]).catch((err) => {
    console.error(err);
});

(profileSchema.js):创建配置文件架构

const mongoose = require("mongoose");

const profileSchema = new mongoose.Schema({
    id: { type: String, require: true, unique: true },
    serverid: { type: String, require: true },
    coins: { type: Number, default: 0 },
    bank: { type: Number }
});

const model = mongoose.model("ProfileModels", profileSchema);

module.exports = model;

(guildMemberAdd.js):创建数据并将其上传到数据库中

const profileModel = require('../models/profileSchema');

module.exports = async(client, discord, member) => {
    let profile = await profileModel.create({
        id: member.id,
        serverid: member.guild.id,
        coins: 0,
        bank: 0
    })

    profile.save();
}

【问题讨论】:

  • guildMemberAdd.js 中的函数实际调用在哪里?
  • 它位于名为 events 的文件夹中。这是在机器人上线时在 index.js 中运行的:pastebin.com/TUd240Dz 还阅读了您的评论,我决定在函数中添加console.log(1),但似乎由于某种原因它没有运行@Joe

标签: javascript node.js mongodb mongoose discord.js


【解决方案1】:

原因与你连接 mongo 的方式有关

默认情况下,mongo 在连接到数据库后会关闭连接。为此,当连接到 keepAlive 选项中的 mongo pass 时,它看起来像:

mongoose.connect(process.env.MONGO_SERVER, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    keepAlive: true
})

这意味着与您的数据库的活动连接将保持打开状态

【讨论】:

  • 感谢您的回答。但是,不幸的是,我的代码仍然存在同样的问题。您还有其他可能的解决方法吗?
  • 尝试向profile.save()添加等待
  • 可悲的是不起作用。
  • 我不太确定是什么导致了您的问题
【解决方案2】:

您正在从 profileSchema.js 导出“模型”并需要 guildMemberAdd.js 中的“profileModel”? 所以从 profileSchema 导入模型而不是 profileModel

【讨论】:

    【解决方案3】:

    修复:确保通过添加 console.log 语句调用 guildMemberAdd 事件。

    如果不是,请检查guildMemberAdd的代码是否与其他事件代码不同。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2016-05-05
    • 2013-12-08
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多