<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Haad Baig</title>
    <description>The latest articles on DEV Community by Haad Baig (@haadbaig).</description>
    <link>https://dev.to/haadbaig</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F940795%2Fa8e45bda-b868-4afc-b69a-7689c7acc0ec.png</url>
      <title>DEV Community: Haad Baig</title>
      <link>https://dev.to/haadbaig</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/haadbaig"/>
    <language>en</language>
    <item>
      <title>Dynamic Query Data/Filter Data on Multiple Fields using GraphQL | MongoDB Mongoose</title>
      <dc:creator>Haad Baig</dc:creator>
      <pubDate>Wed, 05 Oct 2022 12:40:47 +0000</pubDate>
      <link>https://dev.to/haadbaig/dynamic-query-datafilter-data-on-multiple-fields-using-graphql-mongodb-mongoose-ef9</link>
      <guid>https://dev.to/haadbaig/dynamic-query-datafilter-data-on-multiple-fields-using-graphql-mongodb-mongoose-ef9</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2AASQgDTBgm0WqW7rZ7Pwi3Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2AASQgDTBgm0WqW7rZ7Pwi3Q.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Query/Filter data with multiple fields using GraphQL is different yet a very interesting task. Filtering through database has always been a simple yet tricky task. And when filtering includes multiple fields and data is being fetched using GraphQL, things get really messy. This article will help you in filtering data on multiple fields using GraphQL, MongoDB and Mongoose. In fact we will query data or filter data by sending fields and their values as input. This kind of functionality is usually used in e-commerce websites where we apply multiple filter like color, price, region, reviews etc. on searched data. I will use NestJS to do this task but the method is same for NodeJS and is similarly applicable for JavaScript based platforms. I will attach the &lt;a href="http://github.com/mmhaadb" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt; repo link in the end of the article.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;**Disclaimer:** I will skip the project creating part to keep the article short and generic for both Nest JS and Node JS, if you are new to NestJS you can see the start of my previous articles where I have mentioned the method to create a project using Nest CLI, I'll mention the link at end.  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Codebase Explanation:
&lt;/h4&gt;

&lt;p&gt;Here I am using a scenario where we have a database of users and mobile phones. We need to &lt;em&gt;find all the users who have used specific mobile phone&lt;/em&gt;. An array with names of mobile-phone’s ids is maintained in user schema and a separate table with Mobile Phones is present in DB.&lt;/p&gt;

&lt;h4&gt;
  
  
  Method explanation:
&lt;/h4&gt;

&lt;p&gt;We will send data in form of array from GraphQL client. The data will be processed in such a way that the output will be an object of key-value (field_name: value) pair.&lt;/p&gt;

&lt;h4&gt;
  
  
  Resolver for Fetching Data from GraphQL:
&lt;/h4&gt;

&lt;p&gt;Lets first write a resolver to fetch data by calling GraphQL API from GraphQL client.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For NestJS:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Query(() =&amp;gt; [User], {name: "FindWithMultipleFields"})

findWithMultipleFields (
@Args('fields', { type: () =&amp;gt; [String]} ) fields: any,
@Args('values', { type: () =&amp;gt; [[String]]} ) values: any) {

return this.userService.findWithMultipleFields(fields, values);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;For NodeJS:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const resolvers = 
{   
Query: {     
findWithMultipleFields(fields, values) {       
return users.findWithMultipleFields(fields, values);     
}}}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here for Node, we are using JS classes.&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Manipulating Data into key-value Pair:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;Now this is the main part and it is similar for both Node and Nest because it is basic JavaScript task. Now we have out array of &lt;em&gt;fields&lt;/em&gt; and array of &lt;em&gt;values&lt;/em&gt;. We need to process it in such a way that the output is an object of &lt;em&gt;{field: value}&lt;/em&gt; pairs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async findWithMultipleFields (fields: any, value: any): Promise&amp;lt;UserDocument[]&amp;gt; {

const result = value.reduce(function(result, field, index) {
result[fields[index]] = field;
return result;
}, {})
return await this.userModel.find(result);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code will work in a following way.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;**Input:** 
field : [model, price]
value: ['Iphone', 20000]

**Output:**  
result: {{model: 'Iphone', price: 20000}} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since mongoose find function takes an object of key-value pairs, thus we only have to pass the variable &lt;strong&gt;&lt;em&gt;result&lt;/em&gt;&lt;/strong&gt; in Model.find() and we will get the filtered data.&lt;/p&gt;

&lt;h4&gt;
  
  
  Sending Data from GraphQL:
&lt;/h4&gt;

&lt;p&gt;Here I am attaching a screen shot of GraphQL client to showcase the calling of GraphQL API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2Ady0TbyTUvTAejvPBfTChBA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2Ady0TbyTUvTAejvPBfTChBA.png" alt="Query Data/Filter Data on Multiple Fields using GraphQL | MongoDB Mongoose"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here I have passed data in the form of array, even though I am querying on single field here but you can test it and it will for sure work on multiple fields. Output can be seen on the right side of the screenshot attached.&lt;/p&gt;

&lt;p&gt;Here is the &lt;a href="https://github.com/mmhaadb/NestJS-concepts/tree/multiple-field-query-gql" rel="noopener noreferrer"&gt;&lt;strong&gt;link&lt;/strong&gt;&lt;/a&gt;to the final code base, a dummy project that I made to implement this use-case for you.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/haadbaig/NestJS-concepts/tree/multiple-field-query-gql" rel="noopener noreferrer"&gt;GitHub - haadbaig/NestJS-concepts at multiple-field-query-gql&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I hope this was useful for you. Querying data from database by filtering on multiple fields is an important simple yet a tricky task, and when GraphQL is added in the stack, it become more tricky, however, I believe that after reading this article it will become understandingly easy for you.&lt;/p&gt;

&lt;p&gt;If you liked my writing, and find it helpful, do share it with you fellows and leave a comment and claps for me. Also connect me on my &lt;a href="http://linkedin.com/in/haadbaig" rel="noopener noreferrer"&gt;LinkedIn &lt;/a&gt;profile.&lt;/p&gt;

&lt;p&gt;You can also read my previous article on uploading files with GraphQL mutations, here is the link:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/haadbaig/uploading-files-using-graphql-client-to-mongodb-with-nestjs-nodejs-16mj-temp-slug-7422414"&gt;Uploading files using GraphQL Client to MongoDB with NestJS / NodeJS&lt;/a&gt;&lt;/p&gt;

</description>
      <category>query</category>
      <category>graphql</category>
      <category>mongodb</category>
      <category>nestjs</category>
    </item>
    <item>
      <title>Uploading files using GraphQL Client to MongoDB with NestJS / NodeJS</title>
      <dc:creator>Haad Baig</dc:creator>
      <pubDate>Thu, 22 Sep 2022 11:41:54 +0000</pubDate>
      <link>https://dev.to/haadbaig/uploading-files-using-graphql-client-to-mongodb-with-nestjs-nodejs-3aab</link>
      <guid>https://dev.to/haadbaig/uploading-files-using-graphql-client-to-mongodb-with-nestjs-nodejs-3aab</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i5q87R_---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Atb2_bHrui-C6Eq4Tx3i2tg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i5q87R_---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2Atb2_bHrui-C6Eq4Tx3i2tg.png" alt="upload files using Graphql mongodb nestjs nodejs" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This article covers the detailed method to use GraphQL to upload files and process them to store them in MongoDB in BinData format. Framework used is NestJS and technologies used are GraphQL, MongoDB and mongoose. Working with files have always been a tricky task and when it comes to uploading files using graphql, there is very less help available online. Graphql is relatively new and strong data query framework. In this article I have described the details of uploading files using graphql mongodb. Link to complete working code base is available at the end of the article. You will require following package and chrome extension to make this work.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;graphql-upload v12.0.0&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Altair GraphQL Client (chrome extension)&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I tried working with version 14 of &lt;em&gt;graphql-upload&lt;/em&gt; but it seems they are not stable or there are some issue in imports. Also some functions are either missing or they have been changed, however things work just fine with v12.0.0 .&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Setting Up a Project to Upload files with GraphQL:&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;**Disclaimer** : skip this section if you are not using NestJS
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I am working with Nest JS, but you can create your own NodeJS project and things should work just fine in that too. If you have been working with NestJS than you must familiar with @nestcli than it will not be an issue. I’ll right the commands that you need to run.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nest new project_name
____________________________________________________________________ nest g resource ./module/module_name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First command will create a simple nest project. Second command will create a simple boiler plate for a Nest module inside &lt;em&gt;module&lt;/em&gt; directory. When you will run the second command it will ask you to choose layer like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---oMk9FtU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/931/1%2ARUEeyxiiqVdUw_90IFrBHA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---oMk9FtU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/931/1%2ARUEeyxiiqVdUw_90IFrBHA.png" alt="nestjs cli snapshot" width="880" height="164"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You need to choose &lt;em&gt;GraphQL(code-first)&lt;/em&gt;. This will create a simple code base with all configurations intact. However it will not generate *.&lt;em&gt;controller.ts&lt;/em&gt; file because for GraphQL API. You will have to create that file manually and write respective APIs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Installing Dependencies for file upload GrpahQL:
&lt;/h3&gt;

&lt;p&gt;Run following commands inside the directory of NestJS/NodeJS project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For nestjs:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i @nestjs/graphql @nestjs/apollo graphql apollo-server-express graphql-upload@12.0.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;For nodejs:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install graphql graphql-upload@12.0.0 --save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you have to add a line i.e. &lt;strong&gt;&lt;em&gt;app.use(graphqlUploadExpress());&lt;/em&gt;&lt;/strong&gt; in your bootstrap function to tell the NestJS application that incoming request should be executed as GraphQL request. Your &lt;em&gt;main.ts&lt;/em&gt; file will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { graphqlUploadExpress } from 'graphql-upload';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
//app.use(graphqlUploadExpress());
await app.listen(3000);
}
bootstrap();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Node.JS you can add this line in your app.js inside exported function.&lt;/p&gt;

&lt;p&gt;I have commented the line here, the reason is mentioned below. We will uncomment it late at right time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;**Important Disclaimer:** Adding the mentioned line will make your application GraphQL centric and will not execute direct http requests. I have not found any solution yet, but if you want to run http requests you need to comment that line out. 
If you find any solution to that, kindly help the community by commenting the solution.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If have done the previous step, congratulations you are now ready to work with GraphQL and Node/Nest JS.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;**Disclaimer:** It does not seem right to talk about detailed configurations and imports to run the project. I assume that if you are working with Node/Nest you are already familiar with it. However, if you need help with Nest, I have attached github repo of my nest project at the end. You can clone it and play with it to get better understanding.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now I will fast forward to our main problem, which is,&lt;/p&gt;

&lt;h4&gt;
  
  
  How to store files in MongoDB and How to upload file using GraphQL API?
&lt;/h4&gt;

&lt;p&gt;Let me share the code first:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { ArgsType, Field, Float, Int, ObjectType } from '@nestjs/graphql';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document} from 'mongoose';
import { Blob } from 'buffer';
import { Stream } from 'stream';
import { GraphQLUpload, FileUpload } from 'graphql-upload';

export type UserDocument = User &amp;amp; Document;

@ArgsType()@Schema({})
@ObjectType()
export class User {

@Prop()
@Field(() =&amp;gt; String, {nullable: true})
email: string;

@Prop()
@Field( () =&amp;gt; Int, {nullable: true})
age: number;

@Prop({type: Buffer})
@Field(() =&amp;gt; GraphQLUpload,{nullable: true})
image: FileUpload
}
export const UserSchema = SchemaFactory.createForClass(User);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here you have to take a closer look on the datatype of image for MongoDB and GraphQL. For M_ongoDB it is_ &lt;strong&gt;&lt;em&gt;Buffer&lt;/em&gt;&lt;/strong&gt; and for &lt;em&gt;GraphQL it is&lt;/em&gt; &lt;strong&gt;&lt;em&gt;GraphQLUpload.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In my repository, I have followed a certain coding practice of NestJS which is,&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;Controller / Resolver -&amp;gt; Service -&amp;gt; Repository&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;However, all the business logic lies in repository, so I will directly show you the repository’s code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async create(email, age, file): Promise&amp;lt;User&amp;gt; {

console.log(file);
const u = await this.userModel.create({
email,
age,
image: Buffer.from(file).toString('base64')
});
u.save();
return u;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you input a file and set its dataType to &lt;em&gt;Express.Multer.File&lt;/em&gt; in controller.ts, you get the file in following format. The console.log will console output like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3FrlwKSZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AFbVwb-3Ke2BqviP-Wogcfw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3FrlwKSZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AFbVwb-3Ke2BqviP-Wogcfw.png" alt="uplaod file response" width="880" height="181"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The important thing is that &lt;em&gt;buffer&lt;/em&gt; variable. Now what we are gonna do is send this file.buffer in our business logic (repository.ts file) where we will convert it in BinData or base64 to save it in MongoDB as shown in recent mentioned code section. Now you can hit the API with postman by sending image in body in form-data like this,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fBhC-ENu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AjG_LWEf6JbwY6ovjDOdtlA.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fBhC-ENu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AjG_LWEf6JbwY6ovjDOdtlA.jpeg" alt="postman request snapshot" width="880" height="298"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and your data will be saved in MongoDB like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7vCB8qUq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2APQcwv8FlqclZTSqCjzMbpg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7vCB8qUq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2APQcwv8FlqclZTSqCjzMbpg.png" alt="mongodb document snapshot" width="880" height="94"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Till now you should be able to upload a file in BinData by sending Http request from postman to your rest API.&lt;/p&gt;

&lt;p&gt;Now only thing left is to right a mutation and than send a file from GraphQL and upload it to MongoDB.&lt;/p&gt;

&lt;h3&gt;
  
  
  Writing Mutation and Sending File as a input using GraphQL Client:
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;NOTE: Add &lt;strong&gt;app.use(graphqlUploadExpress());&lt;/strong&gt; this line in &lt;strong&gt;&lt;em&gt;main.ts&lt;/em&gt;&lt;/strong&gt; in NestJS. For NodeJS, it will be added in app.js file. Otherwise, graphql will not work.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now in Mutation, you only have to call the function that has business logic in it. But there is one issue, when you send file from Altair Graphql Client the file is received in &lt;em&gt;readStream&lt;/em&gt; format_._ We will have to convert it into buffer first and than send it as a parameter to our &lt;em&gt;create&lt;/em&gt; function.&lt;/p&gt;

&lt;p&gt;For &lt;strong&gt;NestJS,&lt;/strong&gt; the mutation will look like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Mutation(() =&amp;gt; User, {name: 'CreateUser'})
createUser(@Args('email') email: string,
@Args('age') age: number,
@Args({ name: 'file', type: () =&amp;gt; GraphQLUpload }) file: FileUpload) {

console.log(email, age);

console.log(file)

let readStream = file.createReadStream()
let data = ''

// set stream encoding to binary so chunks are kept in binaryreadStream.setEncoding('binary')

readStream.once('error', err =&amp;gt; {
return console.log(err)
})
readStream.on('data', chunk =&amp;gt; (data += chunk))
readStream.on('end', () =&amp;gt; {
// If you need the binary data as a Buffer

// create one from data chunks
console.log(Buffer.from(data, 'binary'))
this.userService.createUser(email, age, Buffer.from(data, 'binary'))
})
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For &lt;strong&gt;NodeJS,&lt;/strong&gt; after converting the file in correct format (buffer), you have to export the function or write the function in an exported class. Than import that class/function in your Mutation file and use it.&lt;/p&gt;

&lt;p&gt;Now the final step is to send file from the GraphQL Client. For this, first you have to download Altair GraphQL Client. link is mentioned.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[https://chrome.google.com/webstore/detail/altair-graphql-client/flnheeellpciglgpaodhkhmapeljopja?hl=en-US](https://chrome.google.com/webstore/detail/altair-graphql-client/flnheeellpciglgpaodhkhmapeljopja?hl=en-US)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once its downloaded, open it and,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;write your mutation query in the code editor.&lt;/li&gt;
&lt;li&gt;Fill in all the variable except the one that will contain file.&lt;/li&gt;
&lt;li&gt;At bottom-left corner, you will see a Green colored active link named &lt;em&gt;“Add Files”&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;clicking it will open file explorer from where you can upload file.&lt;/li&gt;
&lt;li&gt;Now click the send request button and it should work just fine.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The working code directory is available here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;**NOTE:** In my code, If you want to test by sending http request from postman, please comment out the line7 in **main.ts** file.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/haadbaig/NestJS-concepts/tree/using-files-with-gql"&gt;GitHub - haadbaig/NestJS-concepts at using-files-with-gql&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I have tried my best to explain the code in detail, I hope it will help the community and every developer who will come here to find answers to his/her queries. If something is not clear you can always contact me on my linked-in profile. If this article helps you, do not forget to follow my account, give this article multiple claps and share it with your fellow developers.&lt;/p&gt;

&lt;p&gt;Read about how to make &lt;strong&gt;compound keys&lt;/strong&gt; in NestJS with mongoose MongoDB:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/haadbaig/compositecompound-keys-in-mongodb-using-mongoose-in-nestjs-1b5o-temp-slug-6314224"&gt;Composite/Compound Keys in MongoDB using Mongoose in NestJS&lt;/a&gt;&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>nestjs</category>
      <category>nestjstutorial</category>
      <category>graphql</category>
    </item>
    <item>
      <title>Composite/Compound Keys in MongoDB using Mongoose in NestJS</title>
      <dc:creator>Haad Baig</dc:creator>
      <pubDate>Fri, 16 Sep 2022 06:38:31 +0000</pubDate>
      <link>https://dev.to/haadbaig/compositecompound-keys-in-mongodb-using-mongoose-in-nestjs-5cnh</link>
      <guid>https://dev.to/haadbaig/compositecompound-keys-in-mongodb-using-mongoose-in-nestjs-5cnh</guid>
      <description>&lt;h3&gt;
  
  
  Composite/Compound Keys in MongoDB using Mongoose in Nest-JS
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bwpbOTsc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AjH1fdBeeStuuN-mq3OVWCQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bwpbOTsc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AjH1fdBeeStuuN-mq3OVWCQ.png" alt="" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So lately I have been exploring NestJS with Mongo DB and mongoose. Since its a new framework it have been quite a challenge to find any help online. So here I am to provide as much help as I could to make your life easy.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Disclaimer:&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;The GitHub repo I provide was using&lt;/em&gt; multiple databases even though in example I used single database_, that's why you will see the_ Mongoose.Module.forFeature({}) &lt;em&gt;for user and hobby modules in&lt;/em&gt; app.module &lt;em&gt;file however both these mongoose module are using one database i.e.&lt;/em&gt; ‘db1’_ . Don’t get bothered, you can use single database and the code will run just fine._&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So today I will cover the creation of composite/compound keys with one to many relation using mongoose in NestJS. I will also show you the changes you need to do in schema file in various case scenarios. Even though I will provide the entire code base that I will use in this example, but it will help you have some understanding of:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;How to create a simple NestJS app.&lt;/li&gt;
&lt;li&gt;How to create schema in NestJS using mongoose.&lt;/li&gt;
&lt;li&gt;How to create module in NestJS&lt;/li&gt;
&lt;li&gt;What is referenced relation and embedded relation.&lt;/li&gt;
&lt;li&gt;How to write API in NestJS&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Also I will only mention the code of my schema file because to create composite keys, only schema files need to be modified, and than you write your APIs using repository, service and controller file according t your desire and business logic.&lt;/p&gt;

&lt;p&gt;Lets start, First of all create a NestJS application using command:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;nest new application_name&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will provide you with simple boiler plate code to work with. Now create a module, in this example I will use simple User module. You can use command :&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;nest g module module_name&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now lets create a schema. In NestJS, we use decorators throughout the application and as much as they look scary they make our life way too easy. Here is the code for my user-schema:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_export type UserDocument = User &amp;amp; Document;_

_@Schema({_

_})_

_export class User {_

_@Prop()_

_email: string;_

_@Prop()_

_age: number;_

_// @Prop({type: Types.ObjectId, ref: () =&amp;gt; Address, refPath: ‘db2’})_

_// address: Address_

_@Prop()_

_hobby: Hobby[]_

_}_
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;export const UserSchema = SchemaFactory.createForClass(User);&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;UserSchema.index({email: 1, hobby: 1}, {unique: true})&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now here I have defined a schema with an embedded object of another schema object i.e. Hobby. In NestJS, just like node, while using mongoose you need to tell the schema about composite keys by passing the names of entities in index function. The numbers ahead of the names just represent the sorting order. By adding the unique flag in last line, we assign unique constraints to this key. That is, if combination of this key repeats than it will through database error.&lt;/p&gt;

&lt;h3&gt;
  
  
  Here I have made it more complex by creating composite key with array of embedded objects. I will mention the changes you you need to do to create composite keys in different scenarios:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Referenced Objects:&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In side Prop() decorator add the type of the prop as Types.ObjectId and define the reference schema of the prop by passing name as string. Updated line will look like this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;@Prop({type: Types.ObjectId, ref: ‘Hobby’})&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;hobby: Hobby[]&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now before insertion, the database will check the combination of email with the ObjectIDs present in array and if any possible pair repeats, it will through error.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Without any relation:&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To create composite keys using the entities of same schema, In this case lets make a composite key using email and age. All you need to change is the information inside the UserSchema.index function. Updated line will be:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;UserSchema.index({email: 1, age: 1}, {unique: true})&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now before insertion, the database will check the combination of email with the age and if pair repeats, it will through error.&lt;/p&gt;

&lt;p&gt;Now its pretty obvious but I think its its still worth mentioning that:&lt;/p&gt;

&lt;p&gt;We can create composite keys by combining more than 2 entities, all you need to do is tell the schema about the entities that you want to include in composite key in Schema.Index({ },{unique: true}) function.&lt;/p&gt;

&lt;p&gt;That’s all from this article. I hope it turn out to be useful for any of the developer who come here with the hope that they will find answers.&lt;/p&gt;

&lt;p&gt;Here’s link to the working code base:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/haadbaig/NestJS/tree/composite-keys"&gt;GitHub - haadbaig/NestJS&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Reach out to me on Medium/Twitter/LinkedIn if you want me to write an article on any other topic of NestJS.&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>mongoosewithnestjs</category>
      <category>compoundkeysinmongo</category>
      <category>compositekeysinmongo</category>
    </item>
  </channel>
</rss>
