Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

334
Views
How to delete related schema in mongodb using node js (mongoose)

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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});
about 4 years ago · Juan Pablo Isaza Report

0

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 });
  }
};

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!