skip to Main Content

I’m learning back end development and need some help in mongodb, axios

my project is a simple todo app which stores the created tasks in a mongoDB database.

link of repository is here

My problem is when I create a task, I can’t mark it as done or delete it until I refresh the page.

I checked the back end server errors and found the attached highlighted error
enter image description here

I also checked the front end server and found axios error as attached highlighted
enter image description here

By investigation, I realized that ObjectId expects to receive a hex string or integer as argument, but somehow it receives something else as indicated in the error log from axios (undefined) instead of the task id.

How can I solve that problem?

2

Answers


  1. Chosen as BEST ANSWER

    I found out the solution. After adding a todo task, the form is being reset by the code

    this.$refs.form.reset()
    

    All what should be done is use it inside a .then function

    .then(() => {
                    this.$refs.form.reset()
                })
    

  2. The problem is that when you create the task, you add it to the todos array, so it lacks _id, which is undefined when passed to the server, giving the error:

        await axios.post('http://localhost:5200/', {
            title: this.title,
            duration: this.duration,
            priority: this.priority,
            description: this.description,
            status: this.task_done
        })
            .then(
                this.todos.push({
                    title: this.title,
                    duration: this.duration,
                    priority: this.priority,
                    description: this.description,
                    status: this.task_done
                })
            )
    

    https://github.com/HanyTaha61/MEVN-stack-project/blob/master/src/components/todo-form.vue#L118

    The server returns newly created todo id, so add it when pushing to the todos list.

    Try changing the above to this:

    axios.post('http://localhost:5200/', {
            title: this.title,
            duration: this.duration,
            priority: this.priority,
            description: this.description,
            status: this.task_done
        })
        .then(res => {
            this.todos.push({
                _id: res.insertedId,
                title: this.title,
                duration: this.duration,
                priority: this.priority,
                description: this.description,
                status: this.task_done
            });
        })
    

    Also, await is not needed, because you use .then, so you can change that throughout

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