Showing posts with label Node.js. Show all posts
Showing posts with label Node.js. Show all posts

Mongoose - Node.js

schema.js

var mongoose = require('mongoose');
var assert = require('assert');

var schema = mongoose.Schema;
var tutorialSchema = new schema({
   topic:{
       type:String,
       require:true,
       unique:true   },
    description:{
        type:String,
        require:true    }
});

var Tutorials = mongoose.model('tutorials', tutorialSchema);
module.exports = Tutorials;


app.js

var mongoose = require('mongoose');
var assert = require('assert');

var Tutorials = require('./schema.js');

var url = 'mongodb://localhost:27017/MyDb';
mongoose.connect(url);

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'Connection error'));
db.on('open', function () {
   console.log('Connected');
});

var NewTopic = Tutorials({
    topic : 'Express.js',
    description : 'Express Framework',
});

NewTopic.save(function (err) {
    if(err) throw err;

    Tutorials.find(function (err, data) {
        if(err) throw err;
        console.log(data);
    });
});

MongoDB

Setup MongoDB
https://www.youtube.com/watch?v=W9LgdiysafA&index=15&list=PLdtEimKxDSoXDq-zE2YZuJtbERh4x0lxm

>mongod --dbpath="C:\mongodb"

https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
http://www.guru99.com/node-js-mongodb.html

MongoDB In 30 Minutes
https://www.youtube.com/watch?v=pWbMrx5rVBE

Mongo is unable to start
http://stackoverflow.com/questions/41334164/mongo-is-unable-to-start


var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

var url = 'mongodb://localhost:27017/MyDb';
MongoClient.connect(url, function(err, db) {
    assert.equal(err, null);
    console.log("Connected correctly to server.");

    var collection = db.collection('tutorials');

    collection.insertOne({topic: ".Net", description:'Framework From Microsoft'},
        function (err, docs) {
        assert.equal(err, null);
        console.log('Inserted');
    });

    collection.find({}).toArray(function (err, docs) {
        assert.equal(err, null);
        console.log('Found: ');
        console.log(docs);
    });

    db.close();
});

Node.js Express Generator

->npm install express-generator -g

Nevigate to your project folder and execute the following
->express

https://youtu.be/mLhxcvtI2HY?list=PLdtEimKxDSoXDq-zE2YZuJtbERh4x0lxm

Node.js - Routing

var express = require('express');
var app = express();

//for post
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'));

app.get('/', function (req, res) {
    res.send('Hello World');
});

app.get('/aboutus', function (req, res) {
    console.log('Got a get request for About Us');
    res.send('About Us');
});

app.get('/*list', function (req, res) {
    console.log('Got a get request for for list');
    res.send('Page listing');
});

app.get('/products/:productId', function (req, res) {
    res.send("Request id " + req.params.productId);
});

app.get('/form', function (req, res) {
    res.sendFile( __dirname + "/form.html");
})

app.get('/process_get', function (req, res) {
    // Prepare output in JSON format
    response = {
        first_name:req.query.first_name,
        last_name:req.query.last_name
    };
    console.log(response);
    res.end(JSON.stringify(response))
});

app.post('/process_post', urlencodedParser, function (req, res) {
    // Prepare output in JSON format
    response = {
        first_name:req.body.first_name,
        last_name:req.body.last_name
    };
    console.log(response);
    res.end(JSON.stringify(response))
});

var server = app.listen(1234, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port);

});

Node.js - Event Emitter

https://nodejs.org/api/events.html

https://www.youtube.com/watch?v=W8JeWFcceuA&index=6&list=PLdtEimKxDSoXDq-zE2YZuJtbERh4x0lxm

  • Support Node.JS to maintain concurrency
  • Objects That generate events are called event emitters
  • Events module must be imported for creating Event Emitters
  • Event Emitter instance can create new event through emit()
var events = require('events');
// Create an eventEmitter objectvar emitter = new events.EventEmitter();

emitter.on('addUser', function (user, pass) {
   console.log('Added user '+user);
});

var uid = 'imanali';
var pwd = 'tutorialpass';
//add the user emit an eventemitter.emit('addUser', uid, pwd);

Node.js First Application

var http = require("http");

var server =http.createServer(function (req, res) {
    res.writeHead(200, {'Content-type' : 'text/html'});
    res.end('<h2>Hello World</h2>');
});

server.listen(1234, function () {
   console.log('Server running.. at http://localhost:1234');
});