OverwriteModelError: Cannot overwrite `suggestDB` model once compiled - javascript

Hey so I have this error in my Schema and I don't know how to fix it. I also tried looking at the other files, but couldn't find any issue. Can someone help me fix this issue, please? I would really be appreciated.
There are 5 different suggestion files I have made
Schema 1:
const { model, Schema } = require('mongoose');
module.exports = model("suggestDB", new Schema({
GuildID: String,
MessageID: String,
Details: Array,
MemberID: String,
DM: Boolean,
}));
Schema 2:
const { model, Schema } = require('mongoose');
module.exports = model("suggestSetupDB", new Schema({
GuildID: String,
ChannelID: String,
}))
suggest.js file:
const { CommandInteraction, MessageEmbed, MessageActionRow, MessageButton } = require("discord.js");
const suggestDB = require("../../Structures/Schemas/suggestDB");
const suggestSetupDB = require("../../Structures/Schemas/suggestSetupDB");
module.exports = {
name: "suggest",
description: "Create a suggestion.",
usage: "/suggest",
disabled: false,
botCommandChannelOnly: true,
options: [
{
name: "type",
description: "Select a type.",
required: true,
type: "STRING",
choices: [
{
name: "Command",
value: "Command",
},
{
name: "Event",
value: "Event",
},
{
name: "System",
value: "System",
},
{
name: "Other",
value: "Other",
},
],
},
{
name: "suggestion",
description: "Describe your suggestion.",
type: "STRING",
required: true,
},
{
name: "dm",
description: "Set whether the bot will DM you, once your suggestion has been declined or accepted.",
type: "BOOLEAN",
required: true,
}
],
/**
*
* #param {CommandInteraction} interaction
*/
async execute(interaction, client) {
const { options, guildId, member, user } = interaction;
const suggestionsSetup = await suggestSetupDB.findOne({ GuildID: guildId });
var suggestionsChannel;
if(!suggestionsSetup) {
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`❌ This server has not setup the suggestion system.`)]})
} else {
suggestionsChannel = interaction.guild.channels.cache.get(suggestionsSetup.ChannelID)
}
const type = options.getString("type");
const suggestion = options.getString("suggestion");
const DM = options.getBoolean("dm")
const Embed = new MessageEmbed()
.setColor(system_embed_colour)
.setAuthor({name: `${user.tag}`, iconURL: `${user.displayAvatarURL({dynamic: true})}`}, )
.setDescription(`**Suggestion:**\n${suggestion}`)
.addFields(
{name: "Type", value: type, inline: true},
{name: "Status", value: "🕐 Pending", inline: true},
{name: "Reason", value: "Pending", inline: true},
)
try {
const M = await suggestionsChannel.send({embeds: [Embed]});
M.react("👍");
M.react("👎");
await suggestDB.create({GuildID: guildId, MessageID: M.id, Details: [
{
MemberID: member.id,
Type: type,
Suggestion: suggestion,
}],
MemberID: member.id,
DM: DM
})
interaction.reply({embeds: [new MessageEmbed().setColor(system_embed_colour).setDescription(`✅ Your [suggestion](${M.url}) was successfully created and sent to ${suggestionsChannel}`).setFooter({text: "This system was created by M4HD1#6336"})], ephemeral: true})
} catch (err) {
console.log(err);
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`❌ An error occured.`)]})
}
}
}
suggest-setup file:
const { MessageEmbed, Message, CommandInteraction, Client } = require("discord.js");
const DB = require("../../Structures/Schemas/suggestSetupDB");
module.exports = {
name: "suggest-setup",
description: "Set up the channel to where suggestions are sent.",
usage: "/suggest-setup",
permission: "ADMINISTRATOR",
options: [
{
name: "set",
description: "Set the channel where suggestions will be sent.",
type: "SUB_COMMAND",
options: [
{name: "channel", description: "The channel where suggestions will be sent.", type: "CHANNEL", channelTypes: ["GUILD_TEXT"], required: true}
]
},
{
name: "current-channel",
description: "Display the current suggestions channel.",
type: "SUB_COMMAND",
},
],
/**
*
* #param {CommandInteraction} interaction
* #param {Client} client
*/
async execute(interaction, client) {
switch(interaction.options.getSubcommand()) {
case "set":
const channel = interaction.options.getChannel("channel");
try {
await channel.send({embeds: [new MessageEmbed().setColor("AQUA").setDescription(`✅ This channel has been set as a suggestions channel.`)]}).then(async() => {
await DB.findOneAndUpdate({GuildID: interaction.guild.id}, {ChannelID: channel.id}, {new: true, upsert: true})
interaction.reply({embeds: [new MessageEmbed().setColor(admin_embed_colour).setDescription(`✅ ${channel} has successfully been set as the suggestions channel for ${interaction.guild.name}.`)]})
})
} catch (error) {
if(error.message === "Missing Access") {
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`❌ The bot does not have access to this channel.`)]})
} else {
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`${client.emojisObj.animated_cross} An error occured. \n\n \`\`\`${error}\`\`\``).setFooter({text: "This system was created by M4HD1#6336"})]})
}
}
break;
case "current-channel":
const suggestion = await DB.findOne({GuildID: interaction.guild.id})
if(!suggestion)
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`❌ This server has not setup the suggestion system.`)]})
return interaction.reply({embeds: [new MessageEmbed().setColor("AQUA").setDescription(`The suggestions channel is currently set to <#${suggestion.ChannelID}>`)]})
break;
}
},
};
suggestion.js:
const { MessageEmbed, Message, CommandInteraction, Client } = require("discord.js");
const suggestSetupDB = require("../../Structures/Schemas/suggestSetupDB");
const suggestDB = require("../../Structures/Schemas/suggestDB");
module.exports = {
name: "suggestion",
description: "Set up the channel to where suggestions are sent.",
usage: "/suggestion",
permission: "ADMINISTRATOR",
options: [
{
name: "accept",
description: "Accept a suggestion.",
type: "SUB_COMMAND",
options: [
{name: "message-id", description: "The message id of the suggestion you want to accept.", type: "STRING", required: true},
{name: "reason", description: "The reason why this suggestion was accepted.", type: "STRING", required: true}
]
},
{
name: "decline",
description: "Decline a suggestion.",
type: "SUB_COMMAND",
options: [
{name: "message-id", description: "The message id of the suggestion you want to decline.", type: "STRING", required: true},
{name: "reason", description: "The reason why this suggestion was declined.", type: "STRING", required: true}
]
},
],
/**
*
* #param {CommandInteraction} interaction
* #param {Client} client
*/
async execute(interaction, client) {
const messageId = interaction.options.getString("message-id");
const reason = interaction.options.getString("reason");
const suggestionsSetup = await suggestSetupDB.findOne({ GuildID: interaction.guildId });
var suggestionsChannel;
if(!suggestionsSetup) {
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`❌ This server has not setup the suggestion system.`)]})
} else {
suggestionsChannel = interaction.guild.channels.cache.get(suggestionsSetup.ChannelID)
}
const suggestion = await suggestDB.findOne({GuildID: interaction.guild.id, MessageID: messageId})
if(!suggestion)
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`❌ This suggestion was not found in the database.`)]})
const message = await suggestionsChannel.messages.fetch(messageId)
if(!message)
return interaction.reply({embeds: [new MessageEmbed().setColor("RED").setDescription(`❌ This message was not found.`)]})
const Embed = message.embeds[0];
if(!Embed) return;
switch(interaction.options.getSubcommand()) {
case "accept":
Embed.fields[1] = {name: "Status", value: "Accepted", inline: true};
Embed.fields[2] = {name: "Reason", value: `${reason}`, inline: true}
message.edit({embeds: [Embed.setColor("GREEN")], content: `<#${suggestion.MemberID}>`});
if(suggestion.DM) {
const member = client.users.cache.get(suggestion.MemberID);
member.send({embeds: [new MessageEmbed().setColor("GREEN").setTitle("Suggestion 💡").setDescription(`Your suggestion was accepted ✅`).addFields({name: "Suggestion", value: `[link](${message.url})`, inline: true}, {name: "Guild", value: `${interaction.guild.name}`, inline: true}, {name: "Reason", value: `${reason}`, inline: true})]}).catch(() => null)
}
return interaction.reply({embeds: [new MessageEmbed().setColor("AQUA").setDescription(`[Suggestion](${message.url}) was accepted ✅`)], ephemeral: true})
break;
case "decline":
Embed.fields[1] = {name: "Status", value: "Declined", inline: true};
Embed.fields[2] = {name: "Reason", value: `${reason}`, inline: true}
message.edit({embeds: [Embed.setColor("RED")], content: `<#${suggestion.MemberID}>`});
if(suggestion.DM) {
const member = client.users.cache.get(suggestion.MemberID);
member.send({embeds: [new MessageEmbed().setColor("RED").setTitle("Suggestion 💡").setDescription(`Your suggestion was declined. ✅`).addFields({name: "Suggestion", value: `[link](${message.url})`, inline: true}, {name: "Guild", value: `${interaction.guild.name}`, inline: true}, {name: "Reason", value: `${reason}`, inline: true})]}).catch(() => null)
}
return interaction.reply({embeds: [new MessageEmbed().setColor("AQUA").setDescription(`[Suggestion](${message.url}) declined ✅`)], ephemeral: true})
break;
}
},
};
And this is the error I get:
/Users/Aplex/Documents/Aplel/node_modules/mongoose/lib/index.js:505
throw new _mongoose.Error.OverwriteModelError(name);
^
OverwriteModelError: Cannot overwrite `suggestDB` model once compiled.
at Mongoose.model (/Users/Aplex/Documents/Aplel/node_modules/mongoose/lib/index.js:505:13)
at Object.<anonymous> (/Users/Aplex/Documents/Aplel/Structures/Schemas/suggestDB.js:3:18)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/Aplex/Documents/Aplel/Commands/Moderation/suggest.js:2:19)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
Can someone help me find the issue in here?

This Worked for me
const { model, Schema, models } = require('mongoose');
module.exports = models.suggestDB || model("suggestDB", new Schema({
GuildID: String,
MessageID: String,
Details: Array,
MemberID: String,
DM: Boolean,
}));
faced this error in nextjs.
Hope This Helps

Related

discord.js - TypeError [COMMAND_INTERACTION_OPTION_TYPE]: Option "user" is of type: STRING; expected USER

When I run the script for my discord bot and use /warn remove it keeps throwing an error that user is of type string expected USER. It says the error is happening between lines 69:42 and I can't find the issue.
module.exports = {
category: 'Moderation',
description: 'Warn a user',
permissions: ['ADMINISTRATOR'],
slash: true,
guildOnly: true,
options: [
{
type: 'SUB_COMMAND',
name: 'remove',
description: 'Removes a warning from the user',
options: [
{
name: 'user',
type: 'USER',
description: 'The user to remove the warning from',
required: true,
},
{
name: 'id',
type: 'STRING',
description: 'The ID of the warning to remove',
required: true,
},
],
}
],
callback: async ({ guild, member: staff, interaction }) => {
const user = interaction.options.getUser('user')
if (subCommand === 'remove') {
const warning = await warnSchema.findByIdAndDelete(id)
return {
custom: true,
content: `Removed warning ${warning.id} from <#${user?.id}>`,
allowedMentions: {
users: []
}
}
}
}
}
I didn't post all the code because it seemed like it would be too much searching but this is the code that is causing the error.

Bidirectional relationship mongoDB

I have been trying to follow the documentation to make a relationship between movies and categories (also among others that I will mention below, but starting with categories as an example).
Well, below I have the code of the parts of my code and the error response.
models/movie.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const {ObjectId} = mongoose.Schema;
const movieSchema = new Schema(
{
title: {
type: String,
required: true,
},
year: {
type: Number,
required: true,
},
duration: {
type: String,
required: true,
},
rating: {
type: String,
required: true,
},
score: {
type: String,
required: true,
},
category: {
type: ObjectId,
ref: "Category"
},
description: {
type: String,
required: true,
},
director: [{
type: ObjectId,
ref: "Director"
}],
actor: [{
type: ObjectId,
ref: "Actor"
}],
studio: {
type: ObjectId,
ref: "Studio"
},
poster: {
type: String,
required: true,
},
trailer: {
type: String,
required: true,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Movie", movieSchema);
models/category.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const {ObjectId} = Schema;
const categorySchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
movies: [
{
type: ObjectId,
ref: "Movie",
}
]
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Category", categorySchema);
controllers/movie.js
const Movie = require('../models/movie');
const Category = require('../models/category');
const Actor = require('../models/actor');
const Director = require('../models/director');
const Studio = require('../models/studio');
const create = async (req, res) => {
const content = req.body;
const category = await Category.findById(content._id);
const actor = await Actor.findById(content._id);
const director = await Director.findById(content._id);
const studio = await Studio.findById(content._id);
const newMovie = new Movie({
...content,
category,
actor,
director,
studio
});
const savedMovie = await newMovie.save();
category.movies = [...category.movies, savedMovie._id];
await category.save();
actor.movies = [...actor.movies, savedMovie._id];
await actor.save();
director.movies = [...director.movies, savedMovie._id];
await director.save();
studio.movies = [...studio.movies, savedMovie._id];
await studio.save();
res.status(201).json({
message: 'Movie created successfully',
movie: savedMovie
});
};
Now my post request
POST http://localhost:3000/api/v1/movies HTTP/1.1
Content-Type: application/json
{
"title": "The Matrixxx",
"year": 1999,
"duration": "136 min",
"rating": "R",
"score": "8.7",
"category": "6265ba915a8064456ac6231b",
"description": "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.",
"director": ["626502e956cd00fe36692bf9"],
"actor": ["626501fc56cd00fe36692bf2"],
"studio": "626502ac56cd00fe36692bf7",
"poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BNzQzOTk3OTAtNDQ0Zi00ZTVkLWI0MTEtMDllZjNkYzNjNTc4L2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY#._V1_SX300.jpg",
"trailer": "https://www.youtube.com/embed/m8e-FF8MsqU"
}
Response
TypeError: Cannot read property 'movies' of null
at create (C:\Users\default\Desktop\streaming-backend\src\controllers\movie.js:26:36)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Thanks for the answers :3
I think you forgot to use the necessary search fields. In theory, this code should look like this.
const category = await Category.findById(content.category);
const actor = await Actor.findById(content.actor[0]);
const director = await Director.findById(content.director[0]);
const studio = await Studio.findById(content.studio);

joinedAtTimeStamp is showing Nan discord.js

I was coding a userInfo command but when I use the command, the joinedAtTimeStamp is showing <t:NaN:R> in the embed. It's the only problem in this code.
My code:
const { MessageEmbed, ContextMenuInteraction } = require("discord.js");
module.exports = {
name: "userInfo",
aliases: ["user"],
permissions: ["SEND_MESSAGES", "ATTACH_FILES"],
description: "user",
async execute(message, args, cmd, client, Discord, profileData) {
const target = message.mentions.users.first();
if(!args[0]) {
const response2 = new MessageEmbed()
.setColor("RANDOM")
.setAuthor({name: message.author.tag, iconURL: message.author.displayAvatarURL({dynamic: true})})
.setThumbnail(message.author.displayAvatarURL({dynamic: true}))
.addFields(
{name: "ID", value: message.author.id},
{name: "Joined Server", value: `<t:${parseInt(message.author.joinedTimestamp / 1000)}:R>`, inline: true},
{name: "Account Created", value: `<t:${parseInt(message.author.createdTimestamp / 1000)}:R>`, inline: true},
);
message.reply({embeds:[response2]});
}
const response = new MessageEmbed()
.setColor("RANDOM")
.setAuthor({name: target.tag, iconURL: target.displayAvatarURL({dynamic: true})})
.setThumbnail(target.displayAvatarURL({dynamic: true}))
.addFields(
{name: "ID", value: target.id},
{name: "Joined Server", value: `<t:${parseInt(target.joinedTimestamp / 1000)}:R>`, inline: true},
{name: "Account Created", value: `<t:${parseInt(target.createdTimestamp / 1000)}:R>`, inline: true},
);
message.reply({embeds: [response], ephemeral: true})
}
}
I am using discord.js v13 and node 16.
message.author is a User and it doesn't have a joinedTimestamp property, only GuildMembers have. message.member represents the author of the message as a guild member, so you can use that as it will have a joinedTimestamp property.
The reason you see NaN instead of the correct value is because parseInt will return NaN if you try to parse undefined:
console.log('undefined:', parseInt(undefined / 1000, 10));
console.log('3459192421512:', parseInt(3459192421512 / 1000, 10));
The following code should work as expected
.addFields(
{ name: 'ID', value: message.author.id },
{
name: 'Joined Server',
value: `<t:${parseInt(message.member.joinedTimestamp / 1000, 10)}:R>`,
inline: true,
},
{
name: 'Account Created',
value: `<t:${parseInt(message.author.createdTimestamp / 1000, 10)}:R>`,
inline: true,
},
);
As for target, it's the same issue; message.mentions.users.first() is a User. You could create a new variable, e.g. targetMember and assign message.mentions.members.first(), so it will be a GuildMember:
const target = message.mentions.users.first();
const targetMember = message.mentions.members.first();
And then, just replace target:
.addFields(
{ name: 'ID', value: target.id },
{
name: 'Joined Server',
value: `<t:${parseInt(targetMember.joinedTimestamp / 1000, 10)}:R>`,
inline: true,
},
{
name: 'Account Created',
value: `<t:${parseInt(target.createdTimestamp / 1000, 10)}:R>`,
inline: true,
},
);
PS: It's a good idea to use the radix in parseInt. That's why I added 10 as the second parameter in parseInt.
Could you verify the type of target.joinedTimestamp?
It could be that the double conversion you are doing here:
parseInt(target.joinedTimestamp / 1000)
destroyed your number.
(You are converting whatever target.createdTimestamp is to number, dividing it by 100 (making it a floating point number) and then discarding the floating point by converting back to int.)

I get error while making a status command in discord.js

I was making a status command for my discord bot, that returns title, description, and some fields.
I ran into an error. I am using discord.js v13 and Node.js v16.14.2.
My code:
const { MessageEmbed, CommandInteraction, Client, version } = require("discord.js");
const { connection } = require("mongoose");
const os = require("os");
const quick = require('quick.db');
module.exports = {
name: "status",
asliases: [],
permissions: [],
description: "Displays the status of the client",
async execute(message, args, cmd, client, Discord, profileData) {
const messagePing = Date.now();
const endMessagePing = Date.now() - messagePing;
const status = [
"Disconnected",
"Connected",
"Connecting",
"Disconnecting"
];
const embed = new MessageEmbed()
.setColor("RANDOM")
.setTitle(`🌟 PDM Bot Status`)
.setThumbnail('https://imgur.com/IDhLmjc')
.setDescription("in the Skys with PDM Bot")
.addFields(
{ name: "🧠 Client", value: client.tag, inline: true },
{ name: "📆 Created", value: `<t:${parseInt(client.createdTimestamp / 1000, 10)}:R>`, inline: true },
{ name: "✅ Verified", value: "No, Please help us to get Verified :)", inline: true },
{ name: "👩🏻‍💻 Owner", value: 'Pooyan#9627', inline: true },
{ name: "📚 Database", value: 'Connected', inline: true },
{ name: "⏰ Up Since", value: `<t:${parseInt(client.readyTimestamp / 1000, 10)}:R>`, inline: true },
{ name: "🏓 Ping", value: `${endMessagePing}ms , for more information, use -ping command`, inline: true },
{ name: "📃 Commands", value: `45`, inline: true },
{ name: "🏨 Servers", value: `${client.guilds.cache.size}`, inline: true },
{ name: "👦 Users", value: `${client.guilds.cache.memberCont}`, inline: true },
);
message.channel.send({ embeds: [embed], ephemeral: true });
}
}
The error that I ran into because of the embed:
RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values must be non-empty strings.
at Function.verifyString (C:\Users\Pooyan\Desktop\PDM Bot Main\node_modules\discord.js\src\util\Util.js:416:41)
at Function.normalizeField (C:\Users\Pooyan\Desktop\PDM Bot Main\node_modules\discord.js\src\structures\MessageEmbed.js:544:19)
at C:\Users\Pooyan\Desktop\PDM Bot Main\node_modules\discord.js\src\structures\MessageEmbed.js:565:14
at Array.map (<anonymous>)
at Function.normalizeFields (C:\Users\Pooyan\Desktop\PDM Bot Main\node_modules\discord.js\src\structures\MessageEmbed.js:564:8)
at MessageEmbed.addFields (C:\Users\Pooyan\Desktop\PDM Bot Main\node_modules\discord.js\src\structures\MessageEmbed.js:328:42)
at Object.execute (C:\Users\Pooyan\Desktop\PDM Bot Main\commands\status.js:26:14)
at module.exports (C:\Users\Pooyan\Desktop\PDM Bot Main\events\guild\message.js:104:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'EMBED_FIELD_VALUE'
}
I read one or two similar questions/posts but it did not help.
Multiple properties here don't exist, including:
client.tag
client.createdTimestamp
client.guilds.cache.memberCount
Here are the things you should replace them with:
// client.tag
client.user.tag
// client.createdTimestamp
client.user.createdTimestamp
// client.guilds.cache.memberCount
client.guilds.cache.reduce((acc, g) => acc + g.memberCount, 0)

node.js moongose find populate cant access to array

I have this in my backend:
ad = await Ad.find({'company': companyId}).populate('creator');
And when i console.log(ad) i get this:
[
{
connections: [],
status: 1,
_id: 6047c711b1f8cf1c98b2227c,
title: "DOTA: Dragon's Blood | Teaser | Netflix",
company: 6047c6fab1f8cf1c98b2227a,
video: 'uploads\\videos\\7802d640-810a-11eb-83c2-57e23ae6d491.mp4',
creator: {
companies: [Array],
ads: [Array],
_id: 6047c6e7b1f8cf1c98b22279,
name: 'test test',
email: 'test#live.com',
image: 'uploads\\images\\5f3ea850-810a-11eb-83c2-57e23ae6d491.jpeg',
password: '',
__v: 3
},
__v: 0
},
{
connections: [ 6047c745b1f8cf1c98b22280, 6047c83bb1f8cf1c98b22286 ],
status: 1,
_id: 6047c72cb1f8cf1c98b2227f,
title: 'Diretide 2020',
company: 6047c6fab1f8cf1c98b2227a,
video: 'uploads\\videos\\87a97d60-810a-11eb-83c2-57e23ae6d491.mp4',
creator: {
companies: [Array],
ads: [Array],
_id: 6047c6e7b1f8cf1c98b22279,
name: 'test test',
email: 'test#live.com',
image: 'uploads\\images\\5f3ea850-810a-11eb-83c2-57e23ae6d491.jpeg',
password: '',
__v: 3
},
__v: 6
}
]
But when i try to console.log(ad.creator) or console.log(ad.creator.ads) im getting undefined error.. I need this becasue i want to pull some things from ad.creator.ads..
Do i miss something in my code?
I will try to be more specific i tried but i cant figure how to do this:
ad.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const adSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
video: { type: String, required: true },
company: { type: mongoose.Types.ObjectId, required: true, ref: 'Company' },
creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User' },
connections: [{type: mongoose.Schema.ObjectId, ref: 'User'}],
status: {type: Number, default: '1'}
});
module.exports = mongoose.model('Ad', adSchema);
So i need here when i delete this company to also pull all companies from user..
This is user.js
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, minlength: 6 },
image: { type: String, required: true },
companies: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Company' }],
ads: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Ad' }]
});
userSchema.plugin(uniqueValidator);
module.exports = mongoose.model('User', userSchema);
process for deleting company in // i specified part with problem where need to pull ads from user for this:
const deleteCompany = async (req, res, next) => {
const companyId = req.params.cid;
let company;
let ad;
try {
company = await Company.findById(companyId).populate('creator');
ad = await Ad.find({'company': companyId}).populate('creator');
} catch (err) {
const error = new HttpError(
'backend_message13',
500
);
return next(error);
}
if (!company) {
const error = new HttpError('backend_message14', 404);
return next(error);
}
if (company.creator.id !== req.userData.userId) {
const error = new HttpError(
'backend_message15',
401
);
return next(error);
}
const imagePath = company.image;
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await company.remove({ session: sess });
company.creator.companies.pull(company);
await company.creator.save({ session: sess });
// here is the path where is problem i also tried with ad[0]
ad.creator.pull(ad.creator.ads);
await ad.creator.save({ session: sess });
//
await Ad.deleteMany({'company': companyId});
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
err,
500
);
return next(error);
}
fs.unlink(imagePath, err => {
console.log(err);
});
ad.forEach(function (item) {
const videoPath = item.video;
const thumb = item.video.replace("uploads\\videos\\","uploads\\videos\\thumb\\").replace(".mp4", "_screenshot.jpeg");
fs.unlink(videoPath, err => {
console.log(err);
});
fs.unlink(thumb, err => {
console.log(err);
});
});
res.status(200).json({ message: 'backend_message17' });
};
Thanks for help :)
append lean() mean on populate and then see
ad = await Ad.find({'company': companyId}).populate('creator').lean();
The query Ad.find() returns an array - but your code tried to access it as an object:
ad = await Ad.find({'company': companyId}).populate('creator');
console.log(ad.creator)
ad.creator actually is an undefined
Use an index to access required array element:
ad = await Ad.find({'company': companyId}).populate('creator');
console.log(ad[0].creator)
Or switch to Ad.findOne()

Categories