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...