Tuesday, 11 June 2019

Create | Insert | Update | Find | Drop | Delete | Sort | Query | Limit | LookUp Join Aggregate In NodeJS and MongoDB

To create a database in MongoDB, start by creating a MongoClient object,
then specify a connection URL with the correct IP address and the name of the
the database you want to create.

var MongoClient = require('mongodb').MongoClient; var url = "mongodb://127.0.0.1:27017/";


1. Create DataBase In NodeJs | MongoDB

// MongoDB will create the database if
it does not exist, and make a connection to it.

MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Database created!"); db.close(); });




2. Create Collection In NodeJs | MongoDB

// To create a collection in MongoDB, use the createCollection() method:

MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.createCollection("user", function(err, res) { if (err) throw err; console.log("Collection created!"); db.close(); }); });

3. Insert In NodsJs | MongoDB


/*Insert Into Collection The first parameter of the insertOne() method is an object containing the name(s) and value(s) of each field in the the document you want to insert*/ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var myobj = { name: "Company Inc", address: "Highway 37" }; dbo.collection("customers").insertOne(myobj, function(err, res) { if (err) throw err; console.log("1 document inserted"); db.close(); }); }); /*Insert Multiple Documents
To insert multiple documents into a collection in MongoDB,
we use the insertMany() method. The first parameter of the
insertMany() method is an array of objects,
containing the data you want to insert.*/   MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var myobj = [ { name: 'abc', address: 'new 71'}, { name: 'xyz', address: 'lost 4'}, { name: 'jon', address: 'test st 6562'}, ];     dbo.collection("user").insertMany(myobj, function(err, res) { if (err) throw err; console.log("Number of documents inserted: " + res.insertedCount); db.close();     }); });


4. Find In NodeJs | MongoDB

// Full Documentation - https://www.turbo360.co/docs
The first parameter of the findOne() method is a query object. In this example, we use an empty query object, which selects all
documents in a collection MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.collection("customers").findOne({}, function(err, result) { if (err) throw err; console.log(result.name); db.close(); }); }); //The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object. In this example, we use an empty query object, which selects all documents in the collection. MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.collection("customers").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); });

5. Drop Collection In NodeJs | MongoDB

//The drop() method takes a callback function containing the error object and the result parameter which returns true if the collection was dropped successfully, otherwise, it returns false. MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.collection("user").drop(function(err, delOK) { if (err) throw err; if (delOK) console.log("Collection deleted"); db.close(); }); }); //The dropCollection() method takes two parameters: the name of the collection and a callback function MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.dropCollection("customers", function(err, delOK) { if (err) throw err; if (delOK) console.log("Collection deleted"); db.close(); }); });

6. Delete In NodeJs | MongoDB

To delete a record, or document as it is called in MongoDB,
we use the deleteOne() method. Note: If the query finds more than one document,
only the first occurrence is deleted. MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var myquery = { address: 'Mountain 21' }; dbo.collection("customers").deleteOne(myquery, function(err, obj) { if (err) throw err; console.log("1 document deleted"); db.close(); }); }); //To delete more than one document, use the deleteMany() method. Note: Delete all documents were the address starts with the letter "G": MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var myquery = { address: /^G/ }; dbo.collection("customers").deleteMany(myquery, function(err, obj) { if (err) throw err; console.log(obj.result.n + " document(s) deleted"); db.close(); }); });

7.  Sort In  NodeJs |  MongoDB


//Use the sort() method to sort the result in ascending or descending
order. MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var mysort = { name: 1 }; dbo.collection("customers").find().sort(mysort).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); });

8.  Query In NodeJs | MongoDB

// Full Documentation - https://www.turbo360.co/docs
When finding documents in a collection, you can filter the result
by using a query object. The first argument of the find() method is
a query object and is used to limit the search MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var query = { address: "Park Lane 38" }; dbo.collection("user").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); //To find only the documents where the "address" field starts with the
letter "G", use the regular expression /^G/ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var query = { address: /^G/ }; dbo.collection("user").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); });

9. Limit In NodeJs | MongoDB

//The limit() method takes one parameter,
a number defining how many documents to return. MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.collection("customers").find().limit(5).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); });


10. Update In NodeJs | MongoDB


//The first parameter of the updateOne() method is a query
object defining which document to update Note: If the query finds more than one record, only the first occurrence is updated. MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var myquery = { address: "Valley 345" }; var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } }; dbo.collection("user").updateOne(myquery, newvalues, function(err, res) { if (err) throw err; console.log("1 document updated"); db.close(); }); }); Update Only Specific Fields When using the $set operator, only the specified fields are updated: ... var myquery = { address: "Valley 345" }; var newvalues = { $set: { address: "Canyon 123" } }; dbo.collection("user").updateOne(myquery, newvalues, function(err, res) { ... Update Many Documents To update all documents that meet the criteria of the query,
use the updateMany() method. Note: Update all documents where the name starts with the letter "G": MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); var myquery = { address: /^G/ }; var newvalues = {$set: {name: "Minnie"} }; dbo.collection("user").updateMany(myquery, newvalues, function(err, res) { if (err) throw err; console.log(res.result.nModified + " document(s) updated"); db.close(); }); });


11. Join In NodeJs | MongoDB

Join the matching "userAddress" address to the "user" collection

MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.collection('user').aggregate(
[
{ $lookup: { from: 'userAddress', localField: 'address_id', foreignField: '_id', as: 'address' } } ]).toArray(function(err, res) { if (err) throw err; console.log(JSON.stringify(res)); db.close(); });
});


.   




Monday, 21 January 2019

Distance/Time between two lat long Point



Distance between two lat long Point.
     
This routine calculates the distance between two points (given the latitude/longitude of those points). It is being used to calculate the distance between two locations using GeoDataSource (TM) products.

function distance(lat1, lon1, lat2, lon2, unit) {
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = lon1-lon2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) +            Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515;
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist;
}
}

Distance Speed Time Formula

1. s = speed (meters/second)
2. d = distance traveled (meters)
3. t = time (seconds)

To solve for distance use the formula  
                                                   distance = speed x time
Rate and speed are similar since they both represent some distance per unit time like miles per hour or kilometers per hour. You can use the equivalent formula d = rt which means distance equals rate times time.
distance = rate x time
To solve for speed or rate use the formula for speed, s = d/t which means speed equals distance divided by time.
speed = distance/time
To solve for time use the formula for time, t = d/s which means time equals distance divided by speed.
time = distance/speed

Sunday, 1 July 2018

Create your custom HTML DOM in Angular.

you have to implement the methodDomSanitizer from to@angular/platform-browser make your custom element a trusted HTML tag.
You can learn more about Angular elements here
import { DomSanitizer } from '@angular/platform-browser';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-dashboard',
template: `<div [innerHtml]="content"></div>`
})
export class DashboardComponent implements OnInit {
content: any;

constructor(private _domSanitizer: DomSanitizer) {
}

ngOnInit() {
this.content = this._domSanitizer.
bypassSecurityTrustHtml('<h1>This is DonSanitizer</h1>')
}
}




Monday, 11 June 2018

Input Output and forwardRef use for Component Interaction

Component Interaction


This cookbook contains recipes for common component communication scenarios in which two or more components share information.

import { Component, OnInit, Inject, forwardRef } from '@angular/core';

`forwardRef`

import { AppComponent } from '/AppComponent.ts';
@Inject(forwardRef(() => AppComponent))
public _AppComponent: AppComponent)

Pass data from child to parent  with input binding

child =>

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Output() filterObj: EventEmitter<Object> = new EventEmitter<Object>();

this.filterObj.emit(filterObj);

parent =>

<app-user (filterData)="filterData($event)"></app-user>

filterData(filterObject) {
console.log('res>>', filterObject);
}

Pass data from parent to child with input binding

child =>

  1. @Input() modelNmae: any;
  2. @Input('master') masterName: string;
  3. @Input() set filter(modelId) { this.getUserList(modelId) }
  4. get filter() { return this.modelId}

parent =>

  1. @Selector <app-user [filter]="filter"></app-user>

Friday, 8 June 2018

Dynamic Reactive Forms using FormArray.

To work with a FormArray do the following:
  1. Define the items in the array; that is, FormControls or FormGroups.
  2. Initialize the array with items created from data in the data model.
  3. Add and remove items as the user requires.
In module
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

In Component
import {
FormArray,
FormBuilder,
FormGroup,
FormControl,
Validators }
from '@angular/forms';


export class AddUserComponent implements OnInit {
registrationForm: FormGroup;
formErrors = {};
validationMessages = {};
constructor(private _fb: FormBuilder ) { }

ngOnInit() {
this.setFormErrors();
this.creatForms();
this.getDepartmentDDL();
}
getDepartmentDDL() {
// get list of deparment
this.setFormArray(departmentData)
}

setFormErrors() {
this.formErrors = {
'first_Name': '',
'phone_number': '',
'email': '',
'department': '',
'password': '',
'confirm_password': ''
};
this.validationMessages = {
'first_Name': {
'required': 'First name is required.',
'minlength': 'First name must be at least 4 characters long.',
'maxlength': 'First name cannot be more than 20 characters long.'
},
'phone_number': {
'required': 'Phone number is required.',
'pattern': 'Phone number is invalid.',
'maxlength': 'Phone number cannot be more than 20 number long.'
},
'email': {
'required': 'E-mail is required.',
'email': 'E-mail is invalid.',
'maxlength': 'E-mail cannot be more than 100 characters long.'
},
'password': {
'required': 'Password is required.',
'minlength': 'Password must be at least 4 characters long.',
'maxlength': 'Password cannot be more than 35 characters long.'
},
'confirm_password': {
'required': 'Confirm password is required.',
'invalid': 'Password do not match!'
}
};
}
creatForms() {
this.registrationForm = this._fb.group({
first_Name: [this.user.firstname, [Validators.required,
Validators.minLength(4), Validators.maxLength(20)]],
phone_number: ['', [Validators.required,
Validators.pattern('[0-9\+\-\]+'), Validators.maxLength(20)]],
email: [{ value: this.user.email, disabled: this.isEdit },
[Validators.required, Validators.email, Validators.maxLength(100)]],
password: [this.user.password, this.passwordValidator],
confirm_password: [this.user.password, this.cnfPasswordValidator],
department: this._fb.array([]),
});
this.registrationForm.valueChanges.subscribe(data => this.onFormChanged(data));
}
setFormArray(departmentData) {
const arrayItem = departmentData.map(item => {
const obj = Object.assign({}, item);
obj.selectedArr = '';
return this._fb.group(obj)
});
const roleItems = this._fb.array(arrayItem);
this.registrationForm.setControl(department, roleItems);
}
passwordconfirmation(c: AbstractControl): any {
if (!c.parent || !c) { return; }
const pwd = c.parent.get('password');
const cpwd = c.parent.get('confirm_password')

if (!pwd.value || !cpwd.value) { return; }
if (pwd.value !== cpwd.value) {
return { invalid: true };
}
}
clearConfirmPass() {
this.registrationForm.controls['confirm_password'].setValue(null)
}
onFormChanged(data?: any) {
if (!this.registrationForm) { return; }
const form = this.registrationForm;
// tslint:disable-next-line:forin
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
// tslint:disable-next-line:forin
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}

onClickSave() {
const newUser = {};
newUser['firstname'] = this.registrationForm.value['first_Name'];
newUser['Phone'] = this.registrationForm.value['phone_number'];
newUser['email'] = this.registrationForm.value['email'];
newUser['department'] = this.getDepartmentArr();
}
getDepartmentArr() {
const selectedDepartmentArr = [];
this.registrationForm.value.department.map(item => {
if (item.selectedArr) {
selectedDepartmentArr.push({ sfdcId: item.id, Name: item.Name,
status: item.selectedArr })
}
})
return selectedDepartmentArr;
}
}



In HTML


<form #userForm="ngForm" [formGroup]="registrationForm"
(ngSubmit)="onClickSave()" class="form-material" name='userForm'>
<div class="row m-t-10">
<div class="col-6">
<span>First Name
<span class="text-danger">*</span>
</span>
<input type="text" formControlName="first_Name" name="first_Name"
class="form-control">
<small *ngIf="formErrors.first_Name"
class="help-block text-danger">{{ formErrors.first_Name }}</small>
</div>
</div>
<div class="row m-t-10">
<div class="col-6">
<span>Phone
<span class="text-danger">*</span>
</span>
<input formControlName="phone_number" type="text" class="form-control">
<small *ngIf="formErrors.phone_number"
class="help-block text-danger">{{ formErrors.phone_number }}</small>
</div>
<div class="col-6">
<span>Email
<span class="text-danger">*</span>
</span>
<input formControlName="email" type="text" class="form-control">
<small *ngIf="formErrors.email"
class="help-block text-danger">{{ formErrors.email }}</small>
</div>
</div>

<div formArrayName="department" class="border-t vertical-scroll-user">
<table>
<tr class="m-t-5" *ngFor="let role of department; let i=index"
[formGroupName]="i">
<td>
<span>{{i+1}}.</span>
<span>{{role.Name}}</span>
<span class="text-danger">*</span>
</td>
<td>
<input type="radio" id="{{'active-' + i}}" value="1"
formControlName="selectedArr" class="radio-col-light-blue">
<label for="{{'active-' + i}}">Active</label>
</td>
</tr>
</table>
</div>
</form>









Saturday, 26 May 2018

The DevOps lifecycle - it's all about "continuous"

Continuous Integration (CI), Continuous Testing (CT), and Continuous Delivery (CD) are the significant part of DevOps culture. CI includes automating builds, unit tests, and packaging processes while CD is concerned with the application delivery pipeline across different environments. CI and CD accelerate the application development process through automation across different phases, such as build, test, and code analysis, and enable users to achieve end-to-end automation in the application delivery lifecycle:





Thursday, 24 May 2018

Handling 401 Unauthorized using interceptor in Angular 4

In the catch, we can handle any and all errors that occur, of primary interest to this example is the 401 Unauthorized error   https://angular.io/api/common/http/HttpInterceptor.
Create a service 
Ex=> Service name is AuthorizationService

import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Response,
Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { AuthService } from './authentication.service';
import { UsersApi, LoopBackAuth } from '../sdk';
import { Router } from '@angular/router';
import { AppStateService } from './app-state.service';

@Injectable()
export class AuthorizationService extends Http {

constructor(backend: XHRBackend, defaultOptions: RequestOptions,
private router: Router, private auth: LoopBackAuth) {
super(backend, defaultOptions);
}

request(url:string | Request, options?:RequestOptionsArgs):Observable<Response> {
// do whatever like set custom request headers
return super.request(url, options).catch(this.catchErrors());
}

private catchErrors() {
return (res: Response) => {
if (res.status === 401) {
this.auth.clear();
localStorage.clear();
this.router.navigate(['/login']);
}
return Observable.throw(res);
};
}
}

Use this service in Application App module like this.

import { Http, XHRBackend, RequestOptions } from '@angular/http';
import { RouterModule, Router } from '@angular/router';
import { LoopBackAuth } from './../shared/sdk/services/core/auth.service';
import { AuthorizationService } from '../authorization.service';

providers: [
{
provide: Http,
useFactory: (backend: XHRBackend, options: RequestOptions,
router: Router, auth: LoopBackAuth) => {
return new AuthorizationService(backend, options, router, auth);
},
deps: [XHRBackend, RequestOptions, Router, LoopBackAuth]
}
]