Search code examples
javascriptdatabasemongodbdiscorddiscord.js

MongoDB won't create a messageCount value


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


Solution

  • 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.