Mongoose Express CRUD

const mongoose = require("mongoose");
const conn_str = "mongodb://localhost:27017/tcet"
mongoose.connect(conn_str, { useNewUrlParser: true , useUnifiedTopology: true})
	.then( () => console.log("Connected successfully...") )
	.catch( (err) => console.log(err) );

const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	city: String,
	state: String

const user = new mongoose.model("user", userSchema);

/** Express Mongoose Integration **/

const express = require("express");
const app = express();

.get(async (req, res) => {
	let data = await user.find();
.post(async (req, res) => {
	req_data = req.query;
	let obj = new user(req.query)
	let result = await;
.put(async (req, res) => {
	req_data = req.query;
	let result = await user.updateOne({_id:}, {$set : {city:}})
.delete(async (req, res) => {
	let result = await user.deleteOne({_id:})

app.listen(8080, () => {
	console.log("listening 8080...");

MongoDB Cheat Sheet

to start server

to start shell

show dbs;

create/use database
use db_name;

show collections;



show current database;

drop database

db.students.insertOne({_id: 1, name: “shailesh”});

db.students.insertMany([{_id: 2, name: “bagde”}, {_id: 3, name: “sheldon”}]);

select all records

select with projection
db.students.find({},{_id: 0});

exists operator
db.students.find({age: {$exists: false}});

============COMPARISION OPERATORS===========
in operator
db.students.find({_id: {$in: [2,3]}});

not equal operator
db.students.find({_id: {$ne: 2}});

equal operator
db.students.find({_id: {$eq: 2}});

less than $lt

less than equal $lte

greather than $gt

greater than equal $gte

============LOGICAL OPERATORS=============

db.students.find({$and : [{_id : {$gt:1}}, {_id: {$lt: 4}}]})

db.students.find({$or : [{name : “bagde”}, {name: “shailesh”}]})


like case insensitive
db.students.find({name: /h/i})

exact match
db.students.find({name: /^BagDe$/i})

db.students.updateOne({_id: 1}, {$set : {age: 23}});
db.students.updateMany({age : {$exists: false}}, { $set : {age : 25}})

db.students.updateMany({}, {$set: {address: {city: “Mumbai”, state: “MH”}}})
db.students.updateOne({_id: 4}, { $set : {address : {city: “Nagpur”}}});

Unset/Delete Fields
db.students.updateMany({}, {$unset : {city: “”}});

search within sub document
db.students.find({address : { city : “Nagpur”}}).pretty();

Delete Records
db.students.deleteOne({ $or : [{ age : {$lt : 25}}, {name : “sheldon”}] })

===================ORDER BY======================
db.students.find().sort({name: -1})

db.students.find().sort({name: -1}).limit(1)

TCET Session Data

day 2:
javascript: addeventlisterner, fetchapi, validation
mongodb: crud on terminal
nodejs: core, custom module, http module
expressjs: routeing with get,post, put, delete methods
routing with route methods
read query params using res.query
read form data using res.body parser
read raw json using res.body parser
mongodb crud using nodejs (mongoose)

Day 1: JavaScript

variables, datatypes and scope
var x | let x | x

template literals hello ${name}

Conditional Statement if..else

Loops for

String and String methods

Array and Array methods

Math methods


callback function

lambda expression/fatarrow function

Classes and Objects

Array of Objects




Array of JSON

AJAX using fetch API and json-placeholder dummy API

read data from input box
put data in input box
put data in html


events (onclick, onkeyup, onkeydown, onkeypress, onfocus, onchange, onblur)

JavaScript Validation

Load data in table from API (Web Service: json-placeholder) using AJAX call (fetch API)


rsync on windows os

rsync: Failed to exec ssh: No such file or directory(2) on windows

nstalling cwrsync, you are likely to get this error  when you try to run this sample command from the command line.

rsync  -avz  -e  ssh /cygdrive/z/ycsoftware/

“rsync: Failed to exec ssh: No such file or directory(2)” cwrsync

The reason you are getting this is because for some reason rsync is not able to find the path to the ssh.exe file. You should change it to something like this:

C:/cygwin64/bin/rsync.exe -ar . /cygdrive/c/xampp/htdocs/test2/


Angular 4 http post with php

Component or Service:

let data = {'title': 'foo',	'body': 'bar', 'userId': 1};'http://localhost/angular4/angcrud/add_student_action.php', data)
        (res:Response) => {
        err => {
          console.log("Error occured");


Php Script:


$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
//$res_ar = array("foo"=> $_REQUEST['body']);

echo json_encode($request);


<form #studentForm = "ngForm" (ngSubmit)="addStudentRecord(studentForm.value)">
  First name:<br>
  <input type="text" name="firstname" value="Mickey" ngModel>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse" ngModel>
  <input type="submit" value="Submit">


programs on pointers

  1. WAP to exchange values of 2 variables by calling a function exchange
  2. WAP to find length of a string by calling a function lenght
  3. WAP to copy contents of one string into another by calling a function copy.
  4. WAP to reverse contents of a string
  5. WAP to find sum of 10 int values by calling a function sum (passing array as an argument)
  6. WAP to find mean of 10 in values by calling a function MEAN (passing array as an argument)
  7. WAP to dynamically read n values and find their sum
  8. WAP to read information about n students and display them
  9. WAP to find area and circumference of a circle by calling a single function circle
  10. WAP to call functions area and circumference of circle by using function pointer
  11. WAP to count total number of words in a string by calling a function wcount
  12. WAP to read a String and coutn total vowels in that string
  13. WAP to read a string and count total no of digits in that string
  14. WAP to read a string and copy it into another array
  15. WAP to rad a string and reverse that string

Hibernate Native SQL

 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
package corehibernatedemo;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import model.Person;
import model.Student;
import model.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

 * @author Shailesh Sonare
public class CoreHibernateDemo {
     * @param args the command line arguments
    public static void main(String[] args) throws ParseException {
        // TODO code application logic here
        Configuration cfg = new Configuration();
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
        SessionFactory factory = cfg.buildSessionFactory(;
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();
        List users = session.createQuery("from Users").list();
        for (Iterator iterator = users.iterator(); iterator.hasNext();) {
            Users e = (Users);
        Date bdate = new SimpleDateFormat("yyyy-MM-dd").parse("1992-11-15");
        Users  usr = new Users("Sunita", "Sonare", bdate);
        String hql = "UPDATE Users SET dob = :dob WHERE id = :id";
        Query query = session.createQuery(hql);
        query.setParameter("dob", bdate);
        query.setParameter("id", 4);
        //Student s = new Student();
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
        SessionFactory factory = cfg.buildSessionFactory(;
        Session session = factory.openSession();
//        String hql = "FROM Users";
//        List<Users> list = session.createQuery(hql).list();

        String sql = "SELECT first_name, last_name, dob FROM users";
        SQLQuery query = session.createSQLQuery(sql);
        query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); // important when you are using alias <key><value> pair
//        List<Object[]> rows = query.list();
//        for(Object[] row : rows){
//            Users u = new Users(row[0].toString(), row[1].toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(row[2].toString()));
//            System.out.println(u);
//            System.out.println("--------------");
//        }

        List list = query.list();
        for(Object obj : list){
            Map map = (Map)obj;
            System.out.println("" + map.get("first_name"));
            System.out.println("" + map.get("last_name"));
            System.out.println("" + map.get("dob"));

package model;
// Generated 30 May, 2017 5:20:27 PM by Hibernate Tools 4.3.1

import java.util.Date;

 * Users generated by hbm2java
public class Users  implements {

     private Integer id;
     private String firstName;
     private String lastName;
     private Date dob;

    public Users() {

    public Users(String firstName, String lastName, Date dob) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.dob = dob;
    public Integer getId() {
    public void setId(Integer id) { = id;
    public String getFirstName() {
        return this.firstName;
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    public String getLastName() {
        return this.lastName;
    public void setLastName(String lastName) {
        this.lastName = lastName;
    public Date getDob() {
        return this.dob;
    public void setDob(Date dob) {
        this.dob = dob;

    public String toString() {
        return "Users{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + '}';




  1. WAP to read Information about Student and Display it.
    (Information: Roll Number, Name, Age, Sex)
  2. WAP to read Information about an Employee and Display it.
    (Information: EmpNo, Name, Job, Sal)
  3. WAP to read Information about a Worker and Print Payment
    (Information: Name, Wages, WorkingDays)
  4. WAP to read information about 10 workers and print their Payment.
    Print Average Payment
    (Information: Name, Wages, WorkingDays)
  5. WAP to read co-ordinates of end point of a line and find its slope by using the structure
    struct Line{
    int x1, y1, x2, y2;
  6. WAP to read information about student
    (Roll No. Name, Birth Date, Admission Date) by using following structure
    struct date {
    int D, M, Y;
    struct Student {
    int RollNo;
    char name[20];
    struct date bdate;
    struct date admsndate;