Tips for automatically creating a categoryId using ObjectId for a category in Nest JS, Typescript, and Mongoose

book.entity.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { Document } from 'mongoose';
import { Category } from 'src/category/entities/category.entity';

export type BookDocument = Book & Document;

@Schema()
export class Book {
    @Prop()
    title: string;

    @Prop({ type: mongoose.Schema.Types.ObjectId, ref: Category.name })
    categoryId: string;

    @Prop()
    subtitle: string;

    @Prop()
    author: string;

    @Prop()
    published: number;

    @Prop()
    publisher: string;

    @Prop({ default: true })
    isActive: boolean;

    @Prop({ default: false })
    isDelete: boolean;
}

export const BookSchema = SchemaFactory.createForClass(Book);

book.service.ts

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { Book, BookDocument } from './entities/book.entity';

@Injectable()
export class BookService {
constructor(@InjectModel(Book.name) private bookModel:Model<BookDocument>){}

 create( createBookDto: CreateBookDto):Promise<Book> {
    const model=new this.bookModel({
      title:createBookDto.title,
      subtitle:createBookDto.subtitle,
      author:createBookDto.author,
      published:createBookDto.published,
      publisher:createBookDto.publisher
    });

    return model.save();
  }

  findAll():Promise<Book[]> {
    return this.bookModel.find().exec();
  }

send data by post method in postman

{
    "title":"Agile Web Development with Rails",
    "subtitle":"Dive into ES6 and the Future of JavaScript",
    "author":"Sam Ruby, Dave Thomas, David Heinemeier Hansson",
    "published":2010,
    "publisher":"O'Reilly Media"
}

after sending data by post method on postman

{
    "title": "Agile Web Development with Rails",
    "subtitle": "Dive into ES6 and the Future of JavaScript",
    "author": "Sam Ruby, Dave Thomas, David Heinemeier Hansson",
    "published": 2010,
    "publisher": "O'Reilly Media",
    "isActive": true,
    "isDelete": false,
    "_id": "62eb4ee69800880cc4a99557",
    "__v": 0
}

Why isn't the categoryId showing up? I believe it should be generated automatically, but for some reason it's not. Can anyone help me figure this out? Thanks in advance...

category.entity.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';

export type CategoryDocument = Category & Document;

@Schema({ autoIndex: true, collection: `${Category.name}` })
export class Category {
    // Id field.
    _id: MongooseSchema.Types.ObjectId;

    @Prop({ required : true})
    category: string;

    @Prop({ default: true })
    isActive: boolean;

    @Prop({ default: false })
    isDelete: boolean;
}

export const CategorySchema = SchemaFactory.createForClass(Category);

Why isn't the categoryId showing up? I believe it should be generated automatically, but for some reason it's not. Can anyone help me figure this out? Thanks in advance...

Answer №1

Make sure to specify the categoryId

Ensure that your DTO includes information about the category to which this book is assigned.

create( createBookDto: CreateBookDto):Promise<Book> {
    const model=new this.bookModel({
      title:createBookDto.title,
      subtitle:createBookDto.subtitle,
      author:createBookDto.author,
      published:createBookDto.published,
      publisher:createBookDto.publisher,

      categoryId: 'fiction' // Make sure there is a document in the categories collection with _id = fiction
    });

    return model.save();
  }

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 are some methods to troubleshoot $injector type errors in TypeScript?

I'm currently facing an issue with my AngularJS code. Here is a snippet of what I have: this.$injector.get('$state').current.name !== 'login' But, it's giving me the following error message: error TS2339: Property 'c ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

What is the way to declare a prop as optional in Svelte using TypeScript?

I am facing an issue in declaring an optional prop in Svelte with TypeScript. The error message I receive is "Declaration or statement expected". Can someone guide me on how to correctly declare the prop? Definition of My Type: export enum MyVariants { ...

The collaboration between an object literal declaration and an object instantiated through a constructor function

If I declare let bar: Bar; and set it to initialFooConfig;, is bar still considered as type Bar and an object, or does it become an object in literal notation? If the assignment can be done both ways (assuming initialFooConfig is not a constant), what set ...

What is a dynamic component in Vue with Typescript?

I need help implementing type checking for my dynamic component instead of relying on 'any' as a workaround. Can someone guide me through the proper way to achieve this? <script> ... interface { [key: string]: any } const pages: page = ...

The Typescript const assertion translated into Javascript

Is there a way in JavaScript to achieve constant-like behavior similar to TypeScript's const assertion? const arr = [1,2,3,4] as const I am looking for a solution in JavaScript that allows me to create an array that cannot be further mutated. ...

Need assistance with the Angular polyfill.ts file? Wondering where to place the polyfill code and how to manage it effectively?

Currently encountering an error in my Angular project that requires some 'polyfilling'. Due to the restriction on editing webpack.config.js directly, it seems necessary to work with the polyfill.ts file instead. The issue lies in the fact that An ...

`MongoDB impatient for query outcome`

Upon trying to pass the 'db' from my server.js file, where I establish a connection with MongoClient, to routes/api.js for post requests, I encountered an issue. The error message I consistently receive is: TypeError: Cannot read property &apo ...

Unable to establish a connection with Mongoose on localhost

I'm currently working on establishing a connection to my database using mongoose within Apollo-Server-Express. Following the creation of a db in the terminal, I understood that 'mongodb://localhost:27017/*db-name*' serves as the default uri- ...

Angular - Ensuring service completion before proceeding with navigation

I'm currently facing an issue where I need to populate data in a service before navigating, but the navigation is happening before the data is ready. Here's the code in my service: addToken(token) { this.cookieService.set( 'token', ...

Tips for writing an async function using TypeScript

I've been working with Typescript and NLP.js. However, I'm encountering an issue where the argument manager is displaying 'Parameter manager implicitly has an any type'. I attempted to use :, but it didn't solve the problem eff ...

What is the best way to clear a token from SessionStorage upon exiting an Angular application?

I need to clear my sessionStorage every time I exit my application. App Module: export class AppModule implements OnInit, OnDestroy{ constructor(private overlayService: OverlayService, private logger: LoggerService, private userService: UserService, pr ...

What is the process for importing an mp3 file into a TypeScript project?

I'm currently working on a web application using React and TypeScript. My current challenge involves importing an mp3 file for use with the use-sound library, but I keep encountering this error in TypeScript: "Cannot find module '../../as ...

Encountering a 404 error when trying to deploy an Angular application

After following the Angular documentation for deployment, I am deploying my angular application on github pages. The steps I have taken include: 1. Running "ng build --prod --output-path docs --base-href /<project_name>/". 2. Making a copy of docs/ ...

Trouble encountered while using useRef in TypeScript

I'm encountering an issue with the code below; App.tsx export default function App() { const [canvasRef, canvasWidth, canvasHeight] = useCanvas(); return ( <div> <canvas ref={canvasRef} /> </div> ) ...

How require works in Node.js

My current database connection module looks like this: var mongodb = require("mongodb"); var client = mongodb.MongoClient; client.connect('mongodb://host:port/dbname', { auto_reconnect: true }, function(err, db) { if (err) { ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

Oops! An error occurred: Validation Error - Unable to convert value to ObjectID

SCENARIO: It appears that there might be an error in my Mongoose Model or in the parameters being passed to the route. As a newcomer to the angular2 architecture, I may have overlooked something obvious. ISSUE: ISSUE: ValidationError: CastError: Cas ...

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

The type 'Readonly<Ref<Readonly<any>>>' does not have the property 'forEach' available

Having an issue with state management in Vue3 (Pinia) using the Composition API. I successfully retrieved an array called countryCodes and now I want to copy all items from this array into another array called countries defined in the state. However, whe ...