'typescript nestjs Mongoose query, find() object inside an object
In my products schema, the product information is kept in a separate object. In the code below, I am trying to fetch all the products with the trademark Apple, but the code does not work.
async getProductWithStore(productInfoDto: ProductInfoDto) {
try {
const product = await this.productModel
.find({productInfo: productInfoDto})
.populate('store')
return product;
} catch (err) {
return err;
}
}
productInfo.dto.ts
import { IsNotEmpty, IsOptional } from "class-validator";
export class ProductInfoDto {
@IsNotEmpty()
trademark: string;
@IsOptional()
releaseYear: string;
@IsOptional()
model: string;
@IsOptional()
size: string;
@IsOptional()
gender: string;
@IsOptional()
ram: string;
@IsOptional()
screenSize: string;
@IsOptional()
storage: string;
}
product.schema.ts
import { Document, Types } from 'mongoose';
import {Prop, Schema, SchemaFactory} from '@nestjs/mongoose';
import {Store} from '../../store/schemas/store.schema';
import { Category } from 'src/category/schemas/category.schema';
import { ProductInfoDto } from '../dto/product-info.dto';
export type ProductDocument = Product & Document;
@Schema({timestamps:true})
export class Product {
@Prop({required: true})
productName: string;
@Prop({required: true})
description: string;
@Prop({required:true})
stock: number;
@Prop({required:true, type: Types.ObjectId, ref:'Category'})
category: Category;
@Prop({required:true, type:Object})
productInfo: ProductInfoDto
@Prop({required:true})
image:string;
@Prop({required:true, type: Types.ObjectId, ref:'Store'})
store: Store;
@Prop()
sales: number;
@Prop()
rating: number;
@Prop([String])
comments: string[]
}
export const ProductSchema = SchemaFactory.createForClass(Product);
I tried a lot of things from manually typing the information into the code but none of them worked
I found the solution I replaced the .find code with the code below
async getProductWithStore(productInfoDto: ProductInfoDto) {
try {
const product = await this.productModel
.find({'productInfo.trademark':"Apple"})
return product;
}catch(err){
return err
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
