Getting Error while posting a request, ValidationError: TodoTask validation failed: user: Cast to ObjectId failed for value

Issue

i am getting an error while trying to post a todo to the database.
ValidationError: TodoTask validation failed: user: Cast to ObjectId failed for value

  id: 62e02a03c5f6c427c8c3ed44,
  user: {
    _id: 62e02a03c5f6c427c8c3ed44,
    name: 'abc',
    email: '[email protected]',
    password: '$2a$10$C....',
    admin: true,
    date: 2022-07-26T17:53:07.645Z,
    __v: 0
  }
}"(type Object) at path "user"

My function for posting the request :

  const todoTask = await new TodoTask({
    content: req.body.content,
    user: {
      id: req.user._id,
      user: req.user,
    },
  });
  try {
    await todoTask.save(function (err, doc) {
      if (err) throw err;
      console.log("item saved!");
    });
    return res.redirect("/dashboard");
  } catch (err) {
    return res.redirect("/dashboard");
    console.log(err);
  }
};    

Schema is defined as :

  content: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",    
  },
});
module.exports = mongoose.model("TodoTask", todoTaskSchema);

Solution

Since the user property is defined as a ref you should just store the _id in it:

const todoTask = await new TodoTask({
    content: req.body.content,
    user: req.user._id,
  });
  try {
    await todoTask.save(function (err, doc) {
      if (err) throw err;
      console.log("item saved!");
    });
    return res.redirect("/dashboard");
  } catch (err) {
    return res.redirect("/dashboard");
    console.log(err);
  }
};   

When retrieving user’s information you will just need to populate the TodoTask, for example:

const totoTask = await TodoTask.populate('user').exec();

Answered By – lpizzinidev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published