PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 20, 2022

[FIXED] How to create nested object schema with mongoose in nodejs?

 October 20, 2022     express, mongodb, mongoose, node.js, reactjs     No comments   

Issue

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


Solution

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

customFields: [{ type: Object }]


Answered By - NeNaD
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing