Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

Object inside a field of mongoose Schema


I am building an API that gives info about laptops. I am using node and mongoDB with mongoose for this. This is my Schema -

const productSchema = mongoose.Schema(
{
    name: {
        type: String,
        required: [true, 'A product must have a name'],
        unique: true,
    },
},
{
    toJSON: {
        virtuals: true,
    },
    toObject: {
        virtuals: true,
    },
});

I have a name field. I also want a "specs" field that should be an object. I want define rules for the properties in the object of the "specs" field. What I expect to come in the specs field is -

specs: {
   memory: "16gb",
   storage: "512gb",
   "processor": "i7 2.2ghz"
}

So, I want to define rules for 'memory', 'storage', 'processor' in the 'specs' object


Solution

  • If by rules you mean a schema object rules, then possibly something like this would do:

    specs: {
        memory: {
          type: String,
          default: null
        },
        storage: {
          type: String,
          default: null
        },
        processor: {
          type: String,
          default: null
        }
    }
    

    You can add more rules as you need.