Can someone assist me in creating mongoose models?

Currently, I am focused on managing products and categories

These are the two types I have created:

type Category = {
    parent: Category | null;  // Is this acceptable?
    name: String;
};
type Product = {
    categories: Category[];
    name: String;
    qty: Number;
    price: Number;
};

Next, I proceeded to create the models:

// Category model
import { Schema, Types, model } from "mongoose";
import Category from "../types/Category";

const categorySchema = new Schema(
    {
        parent: { type: Types.Array<Category>, required: true },
        name: { type: String, required: true },
    },
    { timestamps: true }
);

export default model("Product", categorySchema);
// Product model
import { Schema, Types, model } from "mongoose";
import Category from "../types/Category";

const productSchema = new Schema(
    {
        categories: { type: Types.Array<Category>, required: true },
        name: String,
        qty: Number,
        price: Number,
    },
    { timestamps: true }
);

export default model("Product", productSchema);

Although VS Code does not display any errors, the server presents the following error upon execution:

TypeError: Invalid schema configuration: MongooseArray is not a valid type at path categories.

Isn't the type of categories in productSchema supposed to be an array of Category?

I also attempted

categories: { type: [Category], required: true }
, but it did not work.

Answer №1

There are numerous approaches to achieve this task, but for simplicity, consider implementing the following:

const productSchema = new Schema(
    {
        categories: { type: [], required: true },
        name: String,
        qty: Number,
        price: Number,
    },
    { timestamps: true }
);

//In cases where you need to store an array or object, or if the category can be left without a specific type

const productSchema = new Schema(
    {
        categories: { [] , required: true },
        name: String,
        qty: Number,
        price: Number,
    },
    { timestamps: true }
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind Webstorm showing duplicate HTTP requests in the console?

Why am I seeing all HTTP requests duplicated in my Webstorm console? Is this normal behavior or indicative of a problem in my node.js Express application? Even when running from the command line, HTTP requests are being logged twice ...

Rendering ReactJs on the server side versus the client side

I'm utilizing react-router for managing both server-side rendering and client-side rendering in my React application. However, I've noticed that the entry point of my app contains the following code: Router.run(routes, Router.HistoryLocat ...

Pass a bespoke object back to the GraphQL resolver

In my Node-Express backend server with GraphQL setup, I am working on providing a custom object as output for a GraphQL resolver. The usual Sequelize approach hasn't worked for me in this case, so I'm exploring new methods. const RootQueryType = ...

Ensure Jest returns the accurate file paths for images in a TypeScript and React environment

I'm currently developing a React application and I have come across an issue with importing images. My usual method of importing images is as follows: import image1Src from 'assets/img1.png"; For testing purposes, I need to be able to make ...

The recent modification made to the date field did not successfully update

I have implemented this schema let docSchema = mongoose.Schema({ name:{type:String,required:true}, }, { timestamps: { createdAt: 'createdAt',updatedAt:'updatedAt' }, collection : 'docs', discriminatorKey : '_type&apo ...

Prevent redundancy by caching svg icons to minimize repeated requests

I have a collection of info cards on my page, each featuring its own unique illustration along with a set of common icons (SVG) for options such as edit, delete, and more. While the illustrations vary from card to card, the icons remain consistent across a ...

A capability that operates on an array of pairs as its parameter, where the primary component of each pair signifies the superior category of the secondary

I'm grappling with developing a TypeScript function that takes an array of Tuples as input. Each tuple should consist of two elements, where the first element acts as a parent type to the second element - essentially, the second element must extend th ...

What is the syntax for typing a mongoose populated field in Typescript?

I am faced with a field that can either be an ID or have a value, and I am attempting to type this field using TypeScript import { InferSchemaType, Schema, Types, model } from 'mongoose'; const personSchema = new Schema({ _id: Schema.Types.Obj ...

Executing two commands in separate directories from an executable: steps to follow

I am currently working on a project that involves a React app with an Express API, each located in different folders. My goal is to create an executable file that can run two specific commands - one in the API folder and another in the app folder. In my a ...

The specified reference token grant value of [object Object] could not be located in the store

Currently, I am working with NestJs along with the oidc passport strategy using identityserver. Below is a snippet of the code: import { UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; ...

Working with TypeORM and MySQL, I utilized the @OneToOne annotation for establishing

Currently, I have set up two tables within my MySQL database: Table 1: Channel CREATE TABLE `channel` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin NOT NULL, `youtubeId` varchar(255) COLLATE utf8_bin NOT NULL, `language ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...

The TypeScript generated definition file (.d.ts) is failing to work properly in conjunction with the typings specified in package.json

I've successfully created a definition file (d.ts) for my TypeScript project using the --declaration argument with the tsc compiler. However, when I attempt to publish the package with the typings property in the npm package.json, this generated defi ...

Exploring the implementation of query parameters in Nest.js

I am currently a freshman in the world of Nest.js. Below is an excerpt from my code: @Get('findByFilter/:params') async findByFilter(@Query() query): Promise<Article[]> { } I have utilized Postman to test this specific router. ht ...

Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable. Below is the layout of the entire page: <% include ../partials/boilerp ...

Implementing an Angular function to close a window when clicking outside of it

I was browsing YouTube and came across a tutorial on how to create a directive that closes a window when clicking outside of it. However, I'm facing an issue with implementing this in my project. I built a simple to-do list application with the abilit ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

What is the process to access the mongo console in WebStorm with a running meteor project?

Recently, I set up meteor and got a basic app running through WebStorm. However, I'm now trying to access the mongo console but can't seem to do it within WebStorm while the project is active. Any suggestions? ...

What could be causing the API link to not update properly when using Angular binding within the ngOnInit method?

Hi there, I'm currently working on binding some data using onclick events. I am able to confirm that the data binding is functioning properly as I have included interpolation in the HTML to display the updated value. However, my challenge lies in upd ...

How to eliminate periods (.) from key strings in JSON data before inserting into MongoDB collections

When trying to insert Json into MongoDB using the C# Driver, I encountered an exception because inserting JSON with keys that contain dots (.) is not allowed. Now, I am looking for a way to replace all dots in keys with underscores (_) or something else... ...