Why can't mongo push my ObjectId in a predefined array?

154 Views Asked by At

I have made my model, it has this Schema:

const CompanySchema = new Schema({
    companyName: {
      type: String,
      required: [true,'the name of the companies working on the game are missing.']
    },
    companyAge: {
      type: Number,
      required: [true,'the age of the company is missing.']
    },
    companyDeveloper:[{
      type: Schema.Types.ObjectId,
      ref: "developer"
    }]
  });

I am trying to push a element into the companyDeveloper array like this:

  addDev(req,res,next){
    const companyId = req.params.id;
    const companyDeveloper = ObjectId.fromString(req.body.companyDeveloper);
    Company.findById({_id: companyId})
    .then((company) => company.companyDeveloper.push({companyDeveloper}))
    .then(company => res.send(company))
    .catch(next);
  }

but I keep getting this error: "error": "ObjectId is not defined".

Before I tried casting it, I got this error Cast to ObjectId failed for value

How can I get this function to work?

printscreen

postman call error

1

There are 1 best solutions below

0
On BEST ANSWER

The ObjectId class from mongoose is defined on Mongoose.Schema.Types.ObjectId

You can require it in the file where you define addDev

const ObjectId = require('mongoose').Schema.Types.ObjectId

or load mongoose into a global where you initialize your node code so you can access it in any file:

global.Mongoose = require('mongoose')

And then use it in your method:

const companyDeveloper = Mongoose.Schema.Types.ObjectId.fromString(req.body.companyDeveloper);