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.
2
Answers
The thing is
$setOnInsert
is only valid forupdate
operations when theupsert
value is set to true. It exists in these methods =>updateOne()
,updateMany
,findAndModify()
. In this case, when it not anupdate
operation, the$setOnInsert
doesn’t run which is why your data doesn’t have themessageCount
value.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
If per guild, you can add GildId item in your schema, and use: