我目前正在嘗試為自定義 Discord 公會命令設定架構:
const GuildCommandsSchema = new mongoose.Schema({
_id: String,
commands: [
{
name: {
type: String,
unique: true,
required: true,
},
action: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
},
],
});
這好嗎,性能方面,還是我可以改進它?我覺得 Mongo 需要查看所有命令,因為即使 'name' 是唯一的,它也無法索引 'commands' 中的任何命令。
如果沒問題,我如何訪問命令中的值?如果存在,我需要通過“名稱”找到正確的命令,否則創建它并添加/更新“操作” “作者”。
我試過這樣的事情:
const updatedCommand = await GuildCommands.findOneAndUpdate(
{ _id },
{
$set: {
[`commands.$[outer].name`]: name,
[`commands.$[outer].action`]: action,
[`commands.$[outer].author`]: author,
},
},
{
arrayFilters: [{ 'outer.name': name }],
}
);
不幸的是,如果命令不存在,則不會創建命令。
謝謝你的幫助
uj5u.com熱心網友回復:
總計的
db.collection.update({},
{
$set: {
"commands.$[c].name": "1",
"commands.$[c].author": "1",
"commands.$[c].action": "1"
}
},
{
arrayFilters: [
{
"c.author": "34"
}
],
multi: true
})
mongoplayground
uj5u.com熱心網友回復:
回答我自己的問題:
我將架構更改為使用 Maps 而不是 Arrays 來提高性能和更好的模型管理。
const GuildCommandsSchema = new mongoose.Schema(
{
_id: String,
commands: {
type: Map,
of: {
_id: false,
name: {
type: String,
required: true,
},
action: {
type: String,
required: true,
},
active: {
type: Boolean,
required: true,
default: true,
},
author: {
type: String,
required: true,
},
},
},
},
{ versionKey: false }
);
查找和更新/創建命令的新查詢也更好 imo:
const findCommand = await GuildCommands.findOne({ _id });
if (!action) {
const getCommand = findCommand.commands.get(name);
if (getCommand) {
message.reply(getCommand.action);
} else {
message.reply(`Cannot find ${name}`);
}
} else {
findCommand.commands.set(name, {
name,
action,
author,
});
findCommand.save();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343587.html
