【问题标题】:Mongoose - Discord saving channels in arraysMongoose - 数组中的 Discord 保存通道
【发布时间】:2021-10-31 11:55:05
【问题描述】:

所以我想首先明确一点,我是猫鼬的初学者。所以我想要关于在数据库中保存数组的帮助。我想将此与 Discord 联系起来。我正在构建一个机器人,我想在其中存储频道的 ID,以使机器人仅响应它们。早些时候我使用的是 Enmap,但为了方便,我转移到了 mongoose。所以我不知道如何存储数组然后将另一个字符串推入该数组。在这种情况下请帮帮我????

【问题讨论】:

  • 你已经尝试了什么? Stack Overflow 不是代码编写服务。这似乎是一种可以用谷歌搜索的问题。
  • 检查this这是一个很常见的问题,即使它没有再次解决问题搜索stackoverflow你会找到你需要的,mongodb文档也很好,不知道mongoose文档。
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: javascript arrays mongodb mongoose discord.js


【解决方案1】:

就是这么简单,在创建模型又名架构后,您只需将类型设置为数组

例子:

const mongoose = require('mongoose')
const schema = mongoose.Schema({
   GuildId: {
     type: String
     required: true
   },

   ChannelIds: {
      type: Array,
      default: []
   }
})

module.exports = mongoose.model("the_model_name", schema)

现在在你的命令中你需要从数据库中获取数据

例子:

// first you will need to define your schema
const schema = require('schema path')

// now we will define data and we will use try catch to not get any errors
let data;
try {
   // Put here the guild id such as the message.guild.id, or anything that is unique for that data
   data = await schema.findOne({ GuildId: ## })

   // if there is no data we want to create a schema for it
   if(!data) {
      data = await schema.create({ GuildId: ## })
   }
} catch(e) {
   // if there is any error log it
   console.log(e)
}

现在我们得到数据后,我们只需推送频道 id,添加它你只需要推送它。

例子

data.ChannelIds.push(/*the channel id or whatever you want to push*/)

最后但并非最不重要的只是保存数据

例子

await data.save()

【讨论】:

  • @Felix 如果对您有帮助,您可以接受答案:D
  • @I_love_vegetables 他问了很多,但从未回过头来:(
  • 是的.. 没关系,我给了你一个 +1 :D
  • @I_love_vegetables 感谢!
猜你喜欢
  • 2018-04-17
  • 2017-12-30
  • 2016-06-01
  • 2017-03-11
  • 1970-01-01
  • 2019-03-05
  • 2020-01-20
  • 1970-01-01
  • 2021-04-20
相关资源
最近更新 更多