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:
JavaScript
x
15
15
1
const {mongoose} = require("mongoose")
2
const mainSchema = require('../models/mainSchema')
3
4
module.exports = {
5
async execute(interaction){
6
7
await new mainSchema ({
8
guild_id: 1234567890,
9
giveaways: [{
10
identifier: 34,
11
destination: 987654321,
12
}],
13
}).save()
14
}
15
Giveaways should be a nested document in the document with the server’s information. My schemas for this looks like this:
JavaScript
1
20
20
1
const mongoose = require("mongoose");
2
3
const giveawaySchema = new mongoose.Schema({
4
identifier: String,
5
destination: String,
6
duration: String,
7
price: String,
8
})
9
10
const mainSchema = new mongoose.Schema({
11
guild_id: String,
12
log_channel_id: String,
13
twitterPreferncesType: String,
14
twitterPreferncesFollowing: Boolean,
15
giveaways: [giveawaySchema],
16
});
17
18
module.exports = mongoose.model("mainSchema", mainSchema);
19
module.exports = mongoose.model("giveawaySchema", giveawaySchema);
20
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:
JavaScript
1
3
1
_id: ObjectId(62b4f6374894fb3e7826ca72)
2
__v:0
3
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:
JavaScript
1
5
1
const Main = mongoose.model("mainSchema", mainSchema);
2
const Giveaway = mongoose.model("giveawaySchema", giveawaySchema);
3
4
module.exports = { Main, Giveaway }
5
Then, try to create the Giveaway
entity before the Main
one, and add that one to the new Main
document:
JavaScript
1
19
19
1
const mongoose = require('mongoose');
2
const { Main, Giveaway } = require('../models/mainSchema');
3
4
module.exports = {
5
async execute(interaction) {
6
const newGiveaway = await Giveaway.create({
7
identifier: 34,
8
destination: 987654321,
9
});
10
11
await Main.create({
12
guild_id: 1234567890,
13
giveaways: [newGiveaway],
14
});
15
16
res.status(200).send('Creation completed');
17
},
18
};
19