castError 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

Looking at the mongoose findById docs, it seems that findById is used to find a document by it’s _id property - here it looks like you should be using find (I’m not sure what you’re trying to do so it might be better for you to use findOne) as you’re searching by the role property.
If you replace await User.findById({role: "manager"}) with await User.find({role: "manager"}) it should work - but bear in mind this is just from having a quick look at the docs, and I don’t actually know what you’re trying to do.
Hope this helps :slight_smile:

1 Like

may be this will explain what am intending to do and you can help.

  1. I want the user to select manager from the front end.
  2. from the backend i want to bring out the userId, this is to check if the manager exist from the model.
  3. this manager are registered manager.
    the reason for searching them is to see if they are registered, bring their email out and the user will finally send a message to the existing manager.
    this has been though, three days of trying please help.

that sounds consistent with what pufferfish is suggesting :+1:


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