Home > OS >  Allowing a Empty Object ID Mongoose,
Allowing a Empty Object ID Mongoose,

Time:01-20

I have two models User and Company. in the User I am storying the Company._ID, to associate users with a company. I have both of the models CRUD capability working as I can create a user associate it with a company and I can Create a company with the Users that I created before adding in the company._ID field to the users. My problem is when I try to leave the company field empty in my form it throws "User validation failed: company: Cast to ObjectId failed for value "" (type string) at path "company" because of "BSONTypeError".

I need a way that I can create a user FIRST and then Create a company but at the same time if the Company already exists be able to register with that company.

This is what ive tried to come up with based on the results its giving me as well as searching the docs

in my model for the user I have put required as false

const { string } = require('joi');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
 
 
const UserSchema = new Schema({
 email:{
     type:String,
     required: true,
     unique: true
    },
 level: String,
 company: {
     type: Schema.Types.ObjectId,
     ref:'Companies',
     required: false
    },
 companyName: String
});
UserSchema.plugin(passportLocalMongoose);
  
module.exports = mongoose.model('User', UserSchema);

and in my form I have no validations.

CodePudding user response:

So the error that you are getting is telling you something. You aren't getting an error because you have omitted the field, you are getting an error because you are assigning an empty string to the field. You need to go into wherever you create the user and only assign a value to company if the value for company is a valid object ID.

Example of potential problem code:

function createUser(info){
    newUser = new User({email: info.email, company: info.company})
    newUser.save()
}

Example of fixed code:

function createUser(info){
    newUser = new User({})
    if(!info.email){
        throw new Error("Email must be provided")
    }
    newUser.email = info.email
    if(info.company){
        newUser.company = info.company
    }
    newUser.save()
}

I'm not sure where you are doing this, if you edit your post with the file you're using to create the user, leave a comment on this answer and I'll take a look, but I guarantee that you are assigning an empty string to user.company at some point.

  • Related