1

I am using mongoose and I want to search multiple collections and delete using the _id property.

i am receiving an array of _id from the user and i am trying to iterate over each element.

var express = require("express");
const mongoose = require("mongoose");
const router = express.Router();


router.delete("/", async (req, res) => {
  let data = req.body; // this is an array of _id from the user


   data.forEach((element) => {
    let models = [];
    models.push(mongoose.models.Furniture);
    models.push(mongoose.models.Clothing);
    models.map((model) => model.findByIdAndRemove(element));
  });
});

module.exports = router;

when I run this I don't receive any errors.

1 Answer 1

1

MongoDB operation is an asynchronous operation. So to get the error or result you need to wait until response returns by the database.

var express = require("express");
const mongoose = require("mongoose");
const router = express.Router();


router.delete("/", async (req, res) => {
  let data = req.body; // this is an array of _id from the user


   data.forEach((element) => {
    let models = [];
    models.push(mongoose.models.Furniture);
    models.push(mongoose.models.Clothing);
    try {
      models.map(async (model) => { await model.findByIdAndRemove(element)});
    } catch (error) { console.log(error) }
  });
});

module.exports = router;
Note: this code is not tested locally but the problem I have solved here
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.