Home > Software design >  Mongoose not saving data according to a function (discord.js)
Mongoose not saving data according to a function (discord.js)

Time:12-27

Today, I decided to make a Discord RPG bot which of course requires profile stats such as coins and the actual users. Therefore, I searched up a tutorial on how I can do this with MongoDB but I am running into one issue. When a guild member joins and the bot is running, the data does not save with no error at all and I am unsure of why this is happening. I have tried troubleshooting the connection status by adding a line console.log(mongoose.connection.readyState) after the bot attempts to connect to the database. This returns 1 which means the connection is fine. I cannot find any other reason why this is caused so I decided to ask a question after hours of thinking.

(index.js): Connecting to the database

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): Creating a profile schema

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): Creating and uploading the data into the database

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

CodePudding user response:

The reason is to do with the way you connect to mongo

BY default mongo closes the connection after connecting to a database. To do this, when connecting to mongo pass in the keepAlive option, so it would look something like:

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

This will then mean an active connection to your database will be kept open

CodePudding user response:

You are exporting 'model' from profileSchema.js and requiring 'profileModel ' from guildMemberAdd.js? so import model from profileSchema and not profileModel

CodePudding user response:

Fix: Make sure the guildMemberAdd event is being called by adding console.log statements. If not, check if guildMemberAdd's code is different to other event codes.

  • Related