Home > OS >  MongoDB won't create a messageCount value
MongoDB won't create a messageCount value

Time:06-14

so I'm making a message count command with discord.js and MongoDB but the "messageCount" value just never gets created. I searched it up and looked at docs but I couldn't find what was wrong.

Codes:

message-counter.js file:

const mongo = require("mongoose")
const schema = require("./schemas/rank/message-count-schema")

module.exports = client => {
    
    client.on('messageCreate', async (message) => {    
        const { author } = message
        const { id } = author
        mongo.connect(
            process.env.MONGO_URI,
            { keepAlive: true }
        )

        const dataQuery = await schema.findOne({ _id: id })
        
        if (!dataQuery) {
            const newSchem = schema(
                {
                    _id: id
                },
                {
                    $setOnInsert: { messageCount: 1 }
                },
                {
                    $inc: { messageCount: 1 }
                },
                {
                    upsert: true
                }
            )
        
            await newSchem.save()
        }
        else {
            dataQuery.updateOne(
                {
                    $inc: { messageCount: 1 }
                },
                {
                    upsert: true
                }
            )
        }
    })
}

message-count-schema.js file:

const mongoose = require('mongoose');

const messageCountSchema = new mongoose.Schema({
    _id: {
        type: String,
        required: true
    },

    messageCount: {
        type: Number,
        required: true
    }
})

module.exports = mongoose.model('message-count', messageCountSchema);

Can someone tell me what's wrong and how to fix it? I'm not asking to be spoon fed, just what's wrong.

enter image description here

CodePudding user response:

The thing is $setOnInsert is only valid for update operations when the upsert value is set to true. It exists in these methods => updateOne(), updateMany, findAndModify(). In this case, when it not an update operation, the $setOnInsert doesn't run which is why your data doesn't have the messageCount value.

CodePudding user response:

Like caladan said before, and adding to that you need .findbyId() if you want to use _id, is your message count is per user or per guild? if per user you can add to your schema a userID String item and use

const member = await message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.author;
const dataQuery = await schema.findOne({ UserID: member.id })
const messagecount = dataQuery.messageCount;
console.log(messagecount)  

If per guild, you can add GildId item in your schema, and use:

const dataQuery = await schema.findOne({ GuildId: message.guild.id })
const messagecount = dataQuery.messageCount;
console.log(messagecount) 
  • Related