我正在尝试使用名为
/moderator
的命令创建一个 Discord 机器人,并使用子命令 /moderator add
将用户 ID 添加到主持人数据库(MongoDB/Mongoose),然后在有人想要运行主持人命令时检查该数据库.
我使用 mongoose 作为模板架构。
这是我的完整代码:
if (!ModeratorSchema.find({ user_id: target.id })) {
ModeratorSchema.create({
username: target.username,
user_id: target.id,
type: interaction.options.getInteger("type")
})
interaction.reply({
content: `Added \`${target} (${target.id})\` as a system moderator with permission level ${interaction.options.getInteger("type")}`,
ephemeral: true
});
client.channels.cache.get(log_channel).send({
content: `\`${target} (${target.id})\` was added as a system moderator by \`${interaction.user.username} (${interaction.user.id})\` with permission level \`${interaction.options.getInteger("type")}\`.`
})
} else {
interaction.reply({
content: "User is already a system moderator.",
ephemeral: true
});
}
这是我用来查看架构是否正常工作的检查,运行后,根本没有输出。
ModeratorSchema.find({ user_id: target.id }), function (err, data) {
if (data) {
info("OK");
} else if (err) {
info("Error")
error(err)
} else {
info("No data")
}
}
任何帮助将不胜感激!预先感谢。
我正在尝试在添加新记录之前检查用户是否已在数据库中。
我这样做是为了代码确实将主持人(用户名、用户 ID、类型)添加到数据库中,但我似乎无法进行验证检查以确保人们不会多次添加用户 ID。我使用 mongoose 作为模式,并使 user_id 唯一,因此虽然系统不会多次添加用户文档,但 Discord 输出仍然无法工作。
就像评论中提到的,您在使用函数时遇到了几个问题。因此,应检查并更改以下内容:
find()
函数返回一个promise,您可能需要阅读有关.find()的更多信息。因此,您的模式返回一个承诺,因此您应该使用 async
和 await
或 then
和 catch
。
其次,您需要使用
.find()
,而不是实际返回数组的.findOne()
,它也可以在.findOne()中找到。
当您使用
target.id
时,您可以使用.findOne()
来检查文档是否存在。如果存在,则显示
const existingModerator = await ModeratorSchema.findOne({ user_id: target.id });
if (existingModerator) {
// return error or message
}
如果不存在,可以使用
.create()
创建一个新文档。
await ModeratorSchema.create({
username: target.username,
user_id: target.id,
// and other params
});
// and you can show success message and other stuff
您也可以尝试使用
try/catch
,让您的代码变得更好。