June 18, 2021

How to query like joins on 2 collections in mongodb using aggregate keyword

To query like JOINS between 2 collections in mongodb, we need to use $aggregate.

Lets see the example:
 
I have 2 collections, one is Employee and another one is Department.
 Employee Collection  
           {    
             "_id" : 1,    
             "name" : {    
                "first" : "Abhi",    
                "last" : "Dev"    
             },    
             "departmentId" : 2
            },    
            {    
             "_id" : 2,    
             "name" : {    
                "first" : "Abc",    
                "last" : "Agrawal"    
             },    
              "departmentId" : 1 
            },    
            {    
             "_id" : 3,    
             "name" : {    
                "first" : "Dhruv",    
                "last" : "Agrawal"    
             },    
             "departmentId" : 1,    
            }  
           }   

Department Collection  
           {    
             "_id" : 1,    
             "name" : "finance" 
            },    
            {    
             "_id" : 2,    
             "name" : "hr" 
            }
           } 

Now I need to fetch employee details for id 2 along with employee's department name. 

The query would be:

db.employee
    .aggregate([
      { $match: { _id: 2 } },
      {
        $lookup: {
          localField: 'departmentId',
          from: 'department',
          foreignField: '_id',
          as: 'departmentName',
        },
      },
      { $unwind: '$departmentName' }
]).toArray()

The output would be:

	{    
         "_id" : 2,    
         "name" : {    
         	"first" : "Abc",    
         	"last" : "Agrawal"    
         },
         "departmentName": {
            "name": "finance"
         }

Hope it helps.

October 30, 2019

How to mock third party libraries and functions in jest using react js


Jest is a library we use for testing JS code whether it's an Angular application or React JS.

Many times we encounter issues while testing code which has third party libraries like mixpanel, moment, redux etc.

To resolve, we need to mock these 3rd party libraries and their respective functions. We need to intercept these libraries by mocking as given below:

1) Create a directory at root as "__mocks__".
2) Let say we need to create mock for moment library. Create a JS file under __mocks__ as moment.js. Keep in mind to have the file name exactly same as declared when importing in source code.
3) Open moment.js file and write below code snippet

const moment = {
  anyFunc: jest.fn()
}
export default moment;

4) Now execute your jest test cases. It will not throw error for moment library.
5) Use can add any mock functions in that file and add expected response and test them.

Hope this helps!