Home > Net >  How to create nested object schema with mongoose in nodejs?
How to create nested object schema with mongoose in nodejs?

Time:10-20

I am creating collections schema in which i should also include customFields array of object which is defined below. But the schema i tried with , creating new Object Id for each property of customFields object. I need help to include customField object inside my collection schema

Object from FRONT_END

{
    "name": "Ali",
    "topic": "Books",
    "description": "Gonnabe nice collection",
    "owner": "63397103eb71457cdff0c244",
    "customFields": [
        {
            "title": "Title",
            "type": ""
        },
        {
            "title": "Description",
            "type": "textarea"
        }
        {
            "title": "Number",
            "type": "number"
        }
    ]
}

COLLECTION POST ROUTE

collectionRoute.post(
  "/",
  JWTAuthMiddleware,
  adminAndUserOnly,
  async (req, res, next) => {
    try {
      const collection = new CollectionModal(req.body);
      console.log(collection);
      await collection.save();
      const newCollection = await UsersModal.findByIdAndUpdate(
        req.body.owner,
        {
          $push: { collections: { ...collection, owner: req.user._id } },
        },
        { new: true }
      );
      res.status(201).send(newCollection);
    } catch (error) {
      next(error);
    }
  }
);

Schema

import mongoose from "mongoose";
const { Schema, model } = mongoose;

const collectionSchema = new Schema(
  {
    name: { type: String },
    description: { type: String },
    topic: { type: String },
    image: { type: String },
    customFields: [
      {
        fieldNumber: { type: Number },
        fieldMultilineText: { type: String },
        fieldType: { type: String },
        fieldChecked: { type: Boolean },
        fieldDate: { type: Date },
      },
    ],
    owner: { type: Schema.Types.ObjectId, ref: "User" },
    items: [{ type: Schema.Types.ObjectId, require: true, ref: "Item" }],
  },
  { timestamps: true }
);

collectionSchema.index({ "$**": "text" });
export default model("Collection", collectionSchema);

USER SCHEMA

const userSchema = new Schema(
  {
    username: { type: String },
    email: { type: String, unique: true },
    password: { type: String },
    role: { type: String, enum: ["user", "admin"], default: "user" },
    status: { type: String, enum: ["active", "blocked"], default: "active" },
    collections: [{ type: Schema.Types.ObjectId, ref: "Collection" }],
  },
  { timestamps: true }
);

Result

Here is req.body in my server

CodePudding user response:

You can specify customFields property to be of type Object, so it will accept whatever object you send.

customFields: [{ type: Object }]
  • Related