skip to Main Content

Somehow, there is a document without an _id in my database. It can be pulled, but cannot be saved or deleted.
The document looks something like the following:

{
  name: 'John Smith',
  key: 'abc123',
  data: [
    'Lorem ipsum',
    'dolor sic amet'
  ]
}

And my Schema looks like the following:

personSchema  = mongoose.Schema({
    name: String,
    data: { type: Array },
    key: String
})

Note, the key field is completely detached from the id and is used internally, and all other documents in the collection have an _id field.

The following code produces the error UnhandledPromiseRejectionWarning: MongooseError: No _id found on document!:

personSchema  = mongoose.Schema({
    name: String,
    data: { type: Array },
    key: String
});
Person = mongoose.model('entries', personSchema);
let entries = await Person.find({key: "abc123"});
let toDelete;
entries.forEach(entry => {
    if(!entry._id){
        toDelete = entry;
    }
});
toDelete.delete();

2

Answers


  1. Chosen as BEST ANSWER

    Ok, so I still have no idea how the document in question was created, but I was able to delete it simply with the following:

    personSchema  = mongoose.Schema({
        name: String,
        data: { type: Array },
        key: String
    });
    Person = mongoose.model('entries', personSchema);
    await Person.deleteOne({key: "abc123"});
    

    And then verifying that the correct entry was deleted.


  2. Your .delete() is asynchronous but you aren’t handling it as asynchronous. Use .deleteOne() instead.

    const mongoose = require('mongoose');
    const personSchema = mongoose.Schema({
        name: String,
        data: { type: Array },
        key: String
    });
    
    const Person = mongoose.model('entries', personSchema);
    
    async function deleteEntry() {
        try {
            let entries = await Person.find({ key: "abc123" });
            let toDelete;
    
            entries.forEach(entry => {
                if (!entry._id) {
                    toDelete = entry;
                }
            });
    
            if (toDelete) {
                await toDelete.deleteOne();
            } else {
                console.log("No document found without an _id or all documents have an _id.");
            }
        } catch (error) {
            console.error("An error occurred:", error);
        }
    }
    
    deleteEntry();
    

    Side note: It is possible to create documents without an _id. But I don’t think that’s what’s going on in your situation.

    const childSchema = new Schema({
      name: String
    }, { _id: false });
    
    const parentSchema = new Schema({
      children: [childSchema],
      familyName: String
    });
    
    const ParentModel = mongoose.model('Parent', parentSchema);
    

    The parent document will have an _id, but the child document will not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search