Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

338
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda