I try to build a database for a giveaway bot using MongoDB. Once a new giveaway is created the bot runs the following code to write the new giveaway into the databank:
const {mongoose} = require("mongoose")
const mainSchema = require('../models/mainSchema')
module.exports = {
async execute(interaction){
await new mainSchema ({
guild_id: 1234567890,
giveaways: [{
identifier: 34,
destination: 987654321,
}],
}).save()
}
Giveaways should be a nested document in the document with the server’s information. My schemas for this looks like this:
const mongoose = require("mongoose");
const giveawaySchema = new mongoose.Schema({
identifier: String,
destination: String,
duration: String,
price: String,
})
const mainSchema = new mongoose.Schema({
guild_id: String,
log_channel_id: String,
twitterPreferncesType: String,
twitterPreferncesFollowing: Boolean,
giveaways: [giveawaySchema],
});
module.exports = mongoose.model("mainSchema", mainSchema);
module.exports = mongoose.model("giveawaySchema", giveawaySchema);
In my Mongo Atlas I have 2 collections mainSchema und giveawaySchema. If I run this code I only get an entry under ‘giveawaySchema’ consisting of this:
_id: ObjectId(62b4f6374894fb3e7826ca72) __v:0
I don’t get any data in the mainSchema collection. Does anyone know what is the error? Thank you for your help in advance.
Advertisement
Answer
You should change your models exports to:
const Main = mongoose.model("mainSchema", mainSchema);
const Giveaway = mongoose.model("giveawaySchema", giveawaySchema);
module.exports = { Main, Giveaway }
Then, try to create the Giveaway entity before the Main one, and add that one to the new Main document:
const mongoose = require('mongoose');
const { Main, Giveaway } = require('../models/mainSchema');
module.exports = {
async execute(interaction) {
const newGiveaway = await Giveaway.create({
identifier: 34,
destination: 987654321,
});
await Main.create({
guild_id: 1234567890,
giveaways: [newGiveaway],
});
res.status(200).send('Creation completed');
},
};