Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require a nested json object in Mongoose Schema

I have the following mongoose schema:

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 1,
    maxlength: 255
  },
  extraData: {
    brand: {
      type: String,
      required: true,
      minlength: 1,
      maxlength: 255
    },
    quantity: {
      type: Number,
      required: true,
      minlength: 1,
      maxlength: 10
    },
   required: true
  }
});

However when i execute it I get the following error: "TypeError: Invalid schema configuration: True is not a valid type at path extraData.required". How can I require the extraData?

like image 577
Giannis Avatar asked Feb 25 '19 20:02

Giannis


People also ask

Can JSON objects be nested?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.

Does Mongoose require schema?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

What is JSON nested?

Nested JSON is simply a JSON file with a fairly big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.

Can I set default value in Mongoose schema?

As mentioned by user whoami, mongoose only sets defaults on insert. If you are using mongoose 4. x and up and MongoDB 2.4. 0 and up you can opt-in to setting default values on update too.


2 Answers

Update: You can use the Subdocument apporach

const extraDataSchema = new mongoose.Schema({
  brand: {
    type: String,
    required: true,
    minlength: 1,
    maxlength: 255
  },
  quantity: {
    type: Number,
    required: true,
    minlength: 1,
    maxlength: 10
  }
});

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 1,
    maxlength: 255
  },
  extraData: {
    type: extraDataSchema, required: true
  }
});
like image 101
dimitris tseggenes Avatar answered Nov 15 '22 03:11

dimitris tseggenes


Check out the Mongoose documentation, In this link you can find an explanation on how to add required to nested properties().
I believe you will need a sub-schema for the nested properties.

like image 23
jakemingolla Avatar answered Nov 15 '22 05:11

jakemingolla