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
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:
And then verifying that the correct entry was deleted.
Your
.delete()
is asynchronous but you aren’t handling it as asynchronous. Use.deleteOne()
instead.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.
The parent document will have an _id, but the child document will not.