0

I am trying to delete a MongoDB document but it's not getting deleted

My schema is

const mongoose = require("mongoose");

const InvestorSchema = mongoose.Schema({
    name: {
        type: String,
        index: true,
        required: true
    },
    logoUrl: {
        type: String,
        required: true
    },
    website: {
        type: String,
        index: true,
        unique: true,
        required: true
    }
});

module.exports = mongoose.model("Investor", InvestorSchema);

and I tried using these but none of them removed the document, Also i'm running on localhost with no users and roles.

// Required models
const InvestorModel = require("mongoose").model("Investor");

const deletedInvestor = InvestorModel.remove({ _id });
const deletedInvestor = InvestorModel.deleteOne({ _id });
const deletedInvestor = InvestorModel.findByIdAndRemove(_id);
const deletedInvestor = InvestorModel.findOneAndRemove({_id});
const deletedInvestor = InvestorModel.findByIdAndDelete(_id);
const deletedInvestor = InvestorModel.findOneAndDelete({_id});

How do i solve this?

7
  • 2
    You need to resolve the returned Promise. i.e deletedInvestor = await InvestorModel.deleteOne({ _id });. Commented Mar 5, 2019 at 10:07
  • Thanks you very much. I thought the await wasn't necessary for deletion. Commented Mar 5, 2019 at 10:11
  • 1
    The await is necessary for any kind of I/O operation that is essentially an "async" operation. For NodeJS just presume ALL I/O is "async". Or of course, read the documentation, because it will tell you. Without await, nothing actually happens. Or rather your program probably exits before it has any opportunity to happen. Commented Mar 5, 2019 at 10:13
  • 1
    Just for completeness nothing happens unless you mongoose.connect() of course. And which also is "async I/O" and yo must await. Commented Mar 5, 2019 at 10:16
  • Thank you. Will await all I/O from now on :) Commented Mar 5, 2019 at 10:17

2 Answers 2

5
  try {
   InvestorModel.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
    } catch (e) {
   console.log(e);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

here the problem is you don't specify what object from the collection you want to remove... So you should use your code implementation like this mate

InvestorModel.remove({ _id: '563237a41a4d68582c2509da' },callback);
InvestorModel.deleteOne({_id: '563237a41a4d68582c2509da' },callback);
InvestorModel.findByIdAndRemove({_id: '563237a41a4d68582c2509da'},callback);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.