somdow
somdow

Reputation: 6318

mongoose findByIdAndDelete / findOneAndRemove not deleting

Im using a basic forms to create/delete info from mongodb. I can create the records fine enough when i submit the form but when i try to remove a record i keep getting this error:

     Cast to ObjectId failed for value " 596f5d7770f6f0d0c2767d3f" at 
path "_id" for model "dwb_notes"

I've looked around and most of the answers i see here on SO speak to multiple instances of the app running or multiple programs running on the same port etc, and other varied solutions that aren't directly related to my problem(i think) but i've tried them anyways to no avail.

I only have one record in the db right now for testing. Here is my model:

function todoNotesModel(){
    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;

    const NotesSchema = new Schema({
        todoCompany : String,
        todoIsFor : String, 
        todoPostedBy : String,
        todoCompleted : Boolean,
        todoPriority : String,
        todoMessages : Array,
        todoTitle : String,    
        todoDate : String
    });

    const NotesModel = mongoose.model("dwb_notes", NotesSchema);

    return NotesModel;
}

module.exports = todoNotesModel();

Using another html form, on load, the delete button is assigned the document id (in this case its 596f5d7770f6f0d0c2767d3f ), and appends it to the delete button. on submit, this id is passed to the delete route via:

app.delete("/notesapi/:tabID", (request, response) => {
    NotesModel.findByIdAndRemove(request.params.tabID, (error, data)=>{
        if(error){
            console.log("error in deleting yo!");
            throw error;
        } else {
            console.log("data all gone and deleted yo");
            response.status(204);

        }
    });
});

when i run a : db.dwb_notes.find().pretty()

i get back :

"_id" : ObjectId("596f5d7770f6f0d0c2767d3f"),
"todoCompany" : "",
"todoIsFor" : "",
"todoPostedBy" : "LOGGED IN USER HERE",
"todoCompleted" : false,
"todoPriority" : "green",
"todoTitle" : "",
"todoDate" : "Wed Jul 19 2017 09:23:56 GMT-0400 (Eastern Daylight Time)",
"todoMessages" : [
        ""
],
"__v" : 0

which shows its there so i don't understand why i'm getting this error. Any ideas?

Upvotes: 1

Views: 13904

Answers (1)

Zander Rootman
Zander Rootman

Reputation: 2208

it looks like your error is printing out an additional space in your MongoID String. Creating an invalid MongoID String.

You can use: string.trim() Documentation

To remove any spaces before or after the string.

Upvotes: 3

Related Questions