how to make complex schema in mongoose

In Mongoose, you can create a complex schema by defining a schema with subdocuments and nesting schemas within them. To create a schema with subdocuments, you need to use the mongoose.Schema.Types.ObjectId type. This type allows you to store an array of objects with different fields. For example, to create a schema for a user object with a list of addresses, you could use the following code:


const userSchema = new mongoose.Schema({
  name: { type: String, required: true},
  addresses: [{
    address1: { type: String, required: true },
    address2: { type: String, required: false },
    city: { type: String, required: true },
    state: { type: String, required: true },
    zip: { type: String, required: true }
  }]
});

This schema defines an object with a name field and an array of address objects. Each address object contains the fields address1, address2, city, state, and zip. You can also nest schemas within each other if you need to create a more complex schema. For example, you could create a schema for a user object with a list of orders like this:


const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  orders: [{
    orderId: { type: String, required: true },
    items: [{
      itemId: { type: String, required: true },
      name: { type: String, required: true },
      quantity: { type: Number, required: true },
      price: { type: Number, required: true }
    }]
  }]
});

This schema defines an object with a name field and an array of order objects. Each order object contains an orderId and an array of item objects. Each item object contains the fields itemId, name, quantity, and price. You can use the highlight.js library to provide syntax highlighting to your code. To do this, you need to include the highlight.js library in your HTML page and then call the hljs.initHighlightingOnLoad() method. Creating a complex schema with Mongoose can be done quickly and easily. By using the mongoose.Schema.Types.ObjectId type, you can create a schema with subdocuments and by nesting schemas within each other you can create even more complex schemas.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe