Assuming that I have the following schemes:
Forum.js
var mongoose = require('mongoose')
const User= require('../user/UserModel');
const Schema=mongoose.Schema;
const ForumSchema = new mongoose.Schema({
forumName: {
type: String
},
forumDescription: {
type: String
},
ownerID: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User'
}},{
timestamps: true
});
const Forum = mongoose.model("Forum", ForumSchema);
module.exports = Forum;
User.js
var mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const UserSchema = new mongoose.Schema({
id: Number,
userID: {
type: String,
unique: true
},
userName: String,
password: String,
isAdministrator: {
type: Boolean,
default: false
}
}, {
timestamps: true
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
the function for deleting a user:
function deleteByUserId(req, res, next) {
let userIDD = req.body.userID;
User.deleteOne({
userID: userIDD
}, function(err, result) {
if (err) {
console.log("Fehler bei Suche: " + err)
} else {
console.log("Alles gut gelaufen.");
res.send(result)
}
})
}
the mongoose-object:
{
"_id": "61886d45235d4829c7e46a3c",
"userID": "admin",
"userName": "Default Administrator Account",
"password": "$2b$10$20QgJgZWXyFOdJL94C1EVOojBBmzKH7sp/6SADG8z0rwAQ6QbSXc.",
"isAdministrator": true,
"createdAt": "2021-11-08T00:20:21.422Z",
"updatedAt": "2021-11-08T00:20:21.422Z",
"__v": 0
}
The OwnerID in the forum schema is a stored user object. The user object that created the forum. Required=true is because a forum must be created by a user. How can I delete the forum object after deleting the user ?
You will have to use some unique identifier in order to "match" between the user and his forums. Let's say that this unique identifier is the user ID so if the user ID is '1234', I guess querying the forum collection for ownerID.userID: '1234' should give you all forums that this user has created.
So you just need to add a simple query for the forums collection as well:
Forum.deleteMany({"ownerID.userID": userIDD})