JackSlayer94
JackSlayer94

Reputation: 855

Mongoose Schema Reference value with default null

I am trying to reference a schema property named grade in my model to another model's id. But there are some instance where I would like to keep it as null. I tried to keep the default as null and tried but I get the following error:

ValidationError: User validation failed: grade: Cast to Array failed for value "" at path "grade"

The following is my code:

import * as mongoose from 'mongoose';
const userSchema = new mongoose.Schema({
  username: String,
  email: { type: String, unique: true, lowercase: true, trim: true },
  password: String,
  school: { type: String, default: null },
  mobile: Number,
  grade: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Grade', default: null }],
  role: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Role' }],
  company: { type: String, default: null },
  designation: { type: String, default: null },
  active: { type: Number, default: 2 },
  url: { type: String, default: null },
  admin: { type: Number, default: 0},
  created: { type: Date, default: Date.now },
  last_active: { type: Date, default: Date.now }
});
const User = mongoose.model('User', userSchema);
export default User;

Is there a way I can keep default values as null though referencing it?

Upvotes: 1

Views: 8274

Answers (2)

Vipul Pandey
Vipul Pandey

Reputation: 1738

The NoSQL is defined in such way if the values are available so it will store in schema otherwise it won't consider it. So If you want to define your keys which might have or haven't values take them as you have taken the role in your above schema else required you can take it as
default: '',

  school: { type: String, default: '' }

Upvotes: 0

Muhammad Soliman
Muhammad Soliman

Reputation: 23776

In MongoDB or NoSQL databases there is no need to make a default value as NULL as it is based on Schemaless architecture however in relational databases you can do that. as long as you don't have a value for the field this column should not be there at all for this row.

Check below those example for 2 rows of your schema:

{username: "jack",  email: "[email protected]", password: "123"}
{username: "msoliman",  email: "[email protected]", password: "123", school: "AB"}

you notice the first row doesn't have school at all, this is exactly the same as you save in relational database school as NULL.

I hope this helps you understand what I mean, if not please leave a comment. if it helps please don't forget to rate my answer

Upvotes: 4

Related Questions