Home > Back-end >  How to delete related schema in mongodb using node js (mongoose)
How to delete related schema in mongodb using node js (mongoose)

Time:09-17

I am trying to delete my 2nd schema which having reference in first schema

ownerSchema.js

var ownerSchema = Schema({
    ownerId   : String,
    fname     : String,
    lname     : String,
    shopPlace : { 
                  type: Schema.Types.ObjectId,
                  ref: 'Shop'
                }
});
var Owner = mongoose.model('Owner', ownerSchema);

shopSchema.js

var shopSchema = Schema({
    _id       : String,
    shopName  : String,
    location  : String,
    startDate : Date,
    endDate   : Date
});
var Shop  = mongoose.model('Shop', shopSchema);

so I am trying to delete my 2nd schema but it only deleting 1st schema

const Owner = require("../models/ownerSchema");
const Shop = require("../models/shopSchema");

const deleteOnwerById = async (req, res) => {
  const { id } = req.params;
  let deletedShop = await Shop.deleteOne({_id:shopPlace}); // I can't delete my shop data
  let deletedTask = await Owner.deleteOne({ ownerId: id });
  } // I can delete owner but not shop detail
};

but it not deleting my related schema

CodePudding user response:

First, delete your Owner using findByIdAndRemove or findOneAndDelete. These methods allow you to specify one or several fields to return from the deleted documents by passing it an optional options object.

let deletedOwner = await Owner.findByIdAndRemove(ownerId, {projection : "shopPlace"});

Then use the owner's shopPlace to delete the corresponding shopPlace :

await Shop.deleteOne({_id:deletedOwner.shopPlace});

CodePudding user response:

You must first get an _id from shopPlace of your owner:

const Owner = require("../models/ownerSchema");
const Shop = require("../models/shopSchema");

const deleteOnwerById = async (req, res) => {
  const { id } = req.params;
  const owner = await Owner.findOne({ ownerId: id }).populate('shopPlace');
  let deletedShop = await Shop.deleteOne({ _id:owner.shopPlace._id });
  let deletedTask = await Owner.deleteOne({ ownerId: id });
  }
};

  • Related