Cast Error message

I am new to node.js, I haven’t been able to find an answer that fixes my problem. What I’m trying to do is create a path that will create a new child object, add it to the parent’s array of children, then return the child object to the requester.The problem that I am running into is that if I pass the string id into findById, node crashes.

CONSOLE ERROR:CastError: Cast to ObjectId failed for value "{ role: 'manager' }" (type Object) at path "_id" for model "user"
 CODE SNIPPET: `app.route("/select").get( async (req, res, next) => {
const {manager} = req.body;
    try {

        const findMangers = await User.findById({role: "manager"})
        if (findMangers) {
            return res.json(findMangers);
        } else if (findMangers.length === 0) {
            return res.json('0 managers')
        } else {
            return res.json("Oops! an error occurr")
    } catch (e) {
        return next(e);
USERMODEL:`const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const userSchema = new Schema({
    type: String
  manager: {
    type: Schema.Types.ObjectId,
    ref: "user"
    type: String,
    required: true
    type: String,
    required: true
    type: String,
    enum: ["manager", "staff"],
    default: "staff"
  deleted: {
    type: Boolean,
    default: false
    type: Date,

const modelUserSchema = mongoose.model("user", userSchema, "Users");

module.exports = modelUserSchema;`

Bsically a user should select manager from the listMager who have register . in other to send them message

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.