Reputation: 13
So I wanna clear it in first that I am a beginner in mongoose. So I wanted a help regarding saving arrays in the database. I want to relate this to Discord. I was building a bot where I want to store the ids of the channels to make the bot respond on them only. Earlier I was using Enmap, but transferred to mongoose for ease. So I don't know how to store arrays then push another string inside that array. Please help me out in this situation 😥
Upvotes: 1
Views: 584
Reputation: 379
It's just so easy, after creating your model aka schema, you just set the type to array
example:
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)
Alright now in your command you will need to get the data from the db
example:
// 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)
}
Now after we got the data we just push the channel id, to add it you just need to push it.
example
data.ChannelIds.push(/*the channel id or whatever you want to push*/)
last but not least just save the data
example
await data.save()
Upvotes: 2