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
Asked
Active
Viewed 458 times
1
-
What have you tried already? Stack Overflow is not a code-writing service. This seems like the kind of question that can be googled. – MrMythical Sep 02 '21 at 01:50
-
check [this](https://stackoverflow.com/questions/33049707/push-items-into-mongo-array-via-mongoose) its so common question, even if its not solve the proble search stackoverflow again you will find what you need, also mongodb documentation is so good, dont know about mongoose docs. – Takis Sep 02 '21 at 04:54
-
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Sep 05 '21 at 07:34
1 Answers
2
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()

UltraX
- 379
- 1
- 5