skip to Main Content

I have this Models

Department.model.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Department = new Schema({
  departmentName: {
    type: String,
    required: true,
  },
  text1: {
    type: String,
    required: false,
  },
  text2: {
    type: String,
    required: false,
  },
  text3: {
    type: String,
    required: false,
  },
  offices: [
    {
      type: Schema.Types.ObjectId,
      ref: "Office",
    },
  ],
  employees: [
    {
      type: Schema.Types.ObjectId,
      ref: "Employees", // Názov referencovaného modelu
      required: true,
    },
  ],
});

const departmentModel = mongoose.model("Departments", Department);
module.exports = departmentModel;

Office.model.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Office = new Schema({
  officeNumber: {
    type: String,
    required: true,
  },
  officeName: {
    type: String,
    required: true,
  },
  text1: {
    type: String,
    required: false,
  },
  text2: {
    type: String,
    required: false,
  },
  text3: {
    type: String,
    required: false,
  },
  officeDepartment: {
    type: Schema.Types.ObjectId, // Typ je ObjectID
    ref: "Departments", // Názov referencovaného modelu
    required: true,
  },
  employees: [
    {
      type: Schema.Types.ObjectId,
      ref: "Employees", // Názov referencovaného modelu
      required: true,
    },
  ],
});

const officeModel = mongoose.model("Offices", Office);
module.exports = officeModel;

and this delete function
deleteRecords.js

// funkcia na vymazanie záznamu
const deleteItem = async (Model, id, res) => {
  try {
    const deletedItem = await Model.findByIdAndDelete(id);

    if (!deletedItem) {
      return res.status(404).json({ error: "Záznam nebol nájdený." });
    }

    // Odstrániť office zo všetkých departments
    if (Model.modelName === "Office") {
      const officeId = deletedItem.offices[0]; // Získame ID kancelárie z pola offices
      await Department.updateMany(
        { offices: officeId },
        { $pull: { offices: officeId } }
      );
    }

    res.status(200).json({ message: "Záznam bol vymazaný" });
  } catch (error) {
    res.status(500).json({ error: "Chyba pri mazaní záznamu." });
  }
};

// Middleware pre routu DELETE
const deleteHandler = (Model) => async (req, res) => {
  const { id } = req.params;
  await deleteItem(Model, id, res); // Musíme tu použiť await, aby sme počkali, kým sa funkcia vykoná
};

// Použitie middleware pre modely

const express = require("express");
const Job = require("../models/Job.model");
const Office = require("../models/Office.model");
const Department = require("../models/Department.model");

const router = express.Router();

//Delete pre Jobs
router.delete("/deleteJob/:id", deleteHandler(Job));

//Delete pre Department
router.delete("/deleteDepartment/:id", deleteHandler(Department));

//Delete pre Office
router.delete("/deleteOffice/:id", deleteHandler(Office));

module.exports = router;

and this is my DeleteButton.vue

<template>
  <q-btn
    dense
    unelevated
    icon="delete"
    color="red"
    @click="deleteRecord"
  ></q-btn>
</template>

<script>
import axios from "axios";

export default {
  props: {
    recordId: {
      type: String,
      required: true,
    },
    modelName: {
      type: String,
      required: true,
    },
  },
  methods: {
    deleteRecord() {
      axios
        .delete(
          `http://localhost:3000/delete${this.modelName}/${this.recordId}`
        )
        .then((response) => {
          console.log("Record deleted successfully!", response.data);
          this.$emit("recordDeleted", this.recordId);
        })
        .catch((error) => {
          console.error("Error deleting record:", error);
        });
    },
  },
};
</script>

My problem is, that when I delete Office, it does’t remove office from Department model. This is output I get when I delete Office:

    {
        "_id": "64b8cdf10a5e94c8275a16b4",
        "departmentName": "trararara",
        "offices": [
            "64b8cdf90a5e94c8275a16b9",
        ],
        "employees": [],
        "__v": 4
    }

this is output I want:

    {
        "_id": "64b8cdf10a5e94c8275a16b4",
        "departmentName": "trararara",
        "offices": [
 
        ],
        "employees": [],
        "__v": 4
    }

2

Answers


  1. Chosen as BEST ANSWER

    Mistake was here

        const officeModel = mongoose.model("Offices", Office);
    module.exports = officeModel;
    

    "Offices" needed to be "Office" :D


  2. Try to declare a pre middleware on the Office schema:

    Office.pre('findOneAndDelete', function(next) {
        Department.updateMany({ offices: this._id }, {
            $pull: { offices: this._id }
        }).exec();
        next();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search