Wednesday, 28 June 2017

What is a promise and how to use with mongoose?

What is a promise and how to use with mongoose?

Question: What is a promise?
A promise is an abstraction for asynchronous programming.
It's an object that proxies for the return value thrown by a function that has to do some asynchronous processing.


Question: How does promise work?
The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve , which must be called when the Promise is resolved (passing a result), and reject , when it is rejected (passing an error)


Question: Give example of promise work in mongoose?
User.update({id: 100}, {$inc: { views: 1 }}).limit(1).exec();
Here execute multiple function in one line is promise.


Question: How to setup mongoose with promise?
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/dbname');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("MongoDB connected Successfully.!");
});



Question: How to Add the data in mongoDb with mongoose?
//Ajax chat messages
var AjaxChatMessageSchema = mongoose.Schema({
    id: Number,
    userID: Number,
    userName: String,
    userRole: String,
    channel: String,
    dateTime: String,
    ip: String,
    text: String,
    status: String,
    vid: Number
}, {collection: 'ajax_chat_messages'});
var AjaxChatMessage = mongoose.model('ajax_chat_messages', AjaxChatMessageSchema);

var saveData={id:11, userName:'testuser',text:'hello user'}
var AjaxChatMessageDtls = new AjaxChatMessage(saveData);
AjaxChatMessageDtls.save(function(err) {
    if (err) {
        console.log("Error while saving the details");
        response.success = 0;
        res.send(response);
    } else {
        response.success = 1;        
        res.send(response);
    }
});



Question: How to do decrement the value by 1?
AjaxChatMessage.update({id: 100}, {$inc: { views: -1 }}).limit(1).exec();



Question: From where we can read more about promise?
http://mongoosejs.com/docs/promises.html


Thursday, 22 June 2017

Express JS - use res.sendFile - use EJS template - Set and Get Session data

setup of EJS template in Express? Get/Set session in Express? How to setup static path in Express

Question: What is res.sendFile() in NodeJS?
It is a simple way to deliver an HTML file to the client.

Example of sendFile
var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);



Question: How to use EJS in Express?
Install the EJS
npm install ejs --save  

Set the Engine as EJS in node server
app.set('view engine', 'ejs');  

render file from node server
app.get('/', function(req, res) {  
  res.render('index', { title: 'The index page!' })
});

Use the parameter in File
<%= title %>



Question: How to Get/Set session in Express?
install session
npm instal express-session --save
Initiaization the session
var session = require('express-session');
app.use(session({
    secret: 'SECRETKEY',
    name: 'SESSION NAME',
    proxy: true,
    resave: true,
    saveUninitialized: true
}));
Set the Session
var sessionData
app.get('/set-the-session', function(req, res) {    
    sessionData = req.session;
    var userDetails = {}    

    //set the session
    sessionData.isLogin = 1;
    sessionData.name = req.body.name;
    sessionData.email = req.body.email;
});
Get the Session
app.get('/get-session', function(req, res) {    
    sessionData = req.session;
    userDetails.isLogin = sessionData.isLogin;
    userDetails.name = sessionData.name;
    userDetails.email = sessionData.email;
    res.send(userDetails);    
});


Question: How to setup static path in Express?
var express = require('express');
var app = express();
app.use(express.static('public'))

create file in : images/kitten.jpg, Now you can access
http://localhost:3000/images/kitten.jpg


Question: Session is not working with ajax call
Explanation
URL: http://127.0.0.1:8080/getphotoaccess?uid=7177
When running in browser, session is working fine.
When running with ajax call, session is not working

Solution
You need to add xhrFields: {: true},in ajax request.
For Example:
$.ajax({
    type: "GET",
    url: "getphotoaccess?uid=7177",            
    dataType: "json",    
    xhrFields: {
            withCredentials: true
       },            
    success: function(resData){

    }
});