Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
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

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Santiago Gelvez Relatório

0

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) 
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda