Snippets Collections
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
const updateStatus = asyncHandler(async (req, res) => {
  console.log("k");
  const { customer, stageFiveId, availableLoansId, status } = req.body;
  console.log(req.body);
  const customerData = await Customer.updateMany(
    {
      _id: customer,
    },
    // db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]})
    {
      $set: { "stage5.$[i].availableLoans.$[j].status": status },
    },
    { arrayFilters: [{ "i._id": stageFiveId }, { "j._id": availableLoansId }] }
  );
  console.log(customerData);
  if (customerData)
    return res.status(200).json({
      success: true,
      message: "Status updated sucessfully!",
    });
  else
    return res.status(400).json({
      success: false,
      message: "Could not able to update Status!",
    });
});
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({},
  [{ $set : { n : {$arrayElemAt:[{ $split: ["$customerName", " "] },1]}} }],

);
db.customers.updateMany({},
  [{ $set : { m : {$arrayElemAt:[{ $split: ["$customerName", " "] },0]}} }],

);
const fetch = require('isomorphic-fetch')


const query = fetch('https://www.freecodecamp.org/page-data/sq/d/4195245674.json')
    .then(resp => resp.json())
    .then(data => {
        // console.log(data)
        return data.data.allChallengeNode.edges.map(e => {
            // console.log(e.node)
            const url_pieces = e.node.fields.slug.split('/')
            return { 
                name: e.node.title, 
                cert: url_pieces[2], 
                section: url_pieces[3], 
                task: url_pieces[4] 
            }
        })
    }).then(q => console.log(q))
await new Promise(r => setTimeout(r, 5000));
const getModels = asyncHandler(async (req, res) => {
  const { modelName } = req.query;
  const dealership = await Dealership.aggregate([
    { $match: { _id: req.user.dealership } },
    {
      $project: {
        models: {
          $filter: {
            input: "$models",
            as: "models",
            cond: {
              $regexMatch: {
                input: "$$models.modelName",
                regex: `^${modelName}`,
                options: "i",
              },
            },
          },
        },
      },
    },
  ]);
  const models = dealership[0].models;
  return res.status(200).json({
    success: true,
    quesData: models,
  });
});
npx gsx-pdf-optimize raw_pdf.pdf optimized_pdf.pdf --dpi=150
// Script-wide timeout for wait and waitAndFind functions (in ms)
var startTime = new Date(),
  thisStep = 0,
  assert = require('assert'),
  Q = require('q'),
  ScriptTimeout = 0,
  MaintenanceMessage = "Script is running during maintenance window";

var log = function(msg) {
  if(typeof msg === "string")
  {
    var totalTimeElapsed = (new Date() - startTime);
    var elapsedSecs =  totalTimeElapsed / 1000;
    console.log('Step ' + thisStep + ': ' + elapsedSecs.toFixed(2) + 's: ' + msg);
    thisStep++;
    
    if(ScriptTimeout > 0 && totalTimeElapsed > ScriptTimeout)
    {
      throw Error('Script timed out. ' + totalTimeElapsed + 'ms is longer than script timeout threshold of ' + ScriptTimeout + 'ms.'); 
    }
  }
};

log("Initialising ...");

 // checks if this run is in within the maintenance window provided
 // @param {string} dayOfWeek - Monday, Tuesday, etc.
 // @param {string} startTime - UTC start time of window in 24hr format
 // @param {string} endTime - UTC end time of window in 24hr format
var checkInMaintenanceWindow = function(dayOfWeek, startTime, endTime)
{
  log("checkInMaintenanceWindow");
  var deferred = Q.defer();
  var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var now = new Date();
  var day = daysOfWeek[now.getUTCDay()];
  
  if(day != dayOfWeek)
  {
    log("Days do not match");
    deferred.resolve("Days do not match"); // not the specified day
  }
  else
  {
    log("Days match, checking times");
    startParts = startTime.split(":");
    var start = new Date(now);
    start.setUTCHours(parseInt(startParts[0]), parseInt(startParts[1]));

    endParts = endTime.split(":");
    var end = new Date(now);
    end.setUTCHours(parseInt(endParts[0]), parseInt(endParts[1]));

    // check if we are in the maintenance window
    if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime())
    {
      log("In maintenance window");
      $http.get("http://www.google.co.uk"); // workaround for monitor produced no traffic error
      deferred.reject(MaintenanceMessage);
    }
    else
    {
      deferred.resolve("Times do not match");
    }
  }  
  return deferred.promise;
};

function shouldDisplayError(message)
{
  return !(typeof message != "undefined" && message !== null && message.length > 0);
}

var buildSecurityOptions = function()
{
  var deferred = Q.defer();
  log("Building security options");
  // build your security options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "https://login.salesforce.com/services/oauth2/token",
    //Define body of POST request.
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    form: {
      grant_type: 'password',
      client_id: 'client ID',
      client_secret: 'Client Secret',
      username: 'username',
      password: 'password'
    }
  };
  
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var getSecurityToken = function(options){
  var deferred = Q.defer();
  log("Retrieving Security Token");
  $http.post(options, function(error, response, body)
  {
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 200 (OK) response code.
      assert.ok(response.statusCode == 200, 'Expected 200 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }    
  });
  return deferred.promise; //promise is returned
};

var extractSecurityToken = function(data){
  log("Extracting Security Token");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  var info = JSON.parse(data);
  log("Security token retrieved successfully");
  deferred.resolve(info.access_token);
  return deferred.promise;
};

var buildApiOptions = function(securityToken){
  var deferred = Q.defer();
  log("Building API options");
  // build your api options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "http://url.com",
    //Define body of PATCH request.
    headers: {'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + securityToken},
    body: {
      "Description": "fooba3r"
    },
    json: true

  };
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var makeApiCall = function(options){
  var deferred = Q.defer();
  log("Making API call");

  //Make PATCH request, passing in options and callback.
  $http.patch(options, function(error, response, body){
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 204 (No Content) response code.
      assert.ok(response.statusCode == 204, 'Expected 204 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }
  });
  return deferred.promise; //promise is returned
};

var validateApiCall = function(body){
  log("Validating Api Call");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  //var info = JSON.parse(body);
  //assert.ok(shouldDisplayError(info.ErrorMessage), "Error Message: " + info.ErrorMessage);
	
  // perform any other validation here
  log("Completed successfully");
  deferred.resolve();
  return deferred.promise;
};

checkInMaintenanceWindow("Friday", "00:00", "01:30")
.then(function(){
  return buildSecurityOptions()
  .then(getSecurityToken)
  .then(extractSecurityToken)
  .then(buildApiOptions)
  .then(makeApiCall)
  .then(validateApiCall);
},
function(message){
  if(message != MaintenanceMessage)
  {
    throw new Error(MaintenanceMessage);
  }
  else
  {
    log(message);
  }
})
.done();
//Import the `assert` module to validate results.
var assert = require('assert');

var options = {
    url: "https://some_url.com",
        "headers": {
          "oauth_clientid": 123,
          
          },
        //"timeout": 15000
        };

$http.get(options, function(error, response, body) {
    console.log(response.statusCode + " status code")
    assert.ok(response.statusCode == 401, 'Expected 401 OK response');  
      });
sudo forever start --sourceDir /opt/bitnami/projects/nesk_back -c "npm run prod" /
var readline = require("readline");
var rl = readline.createInterface({input: process.stdin, output: process.stdout});

var program = function(){
    rl.question("type question", function(answer) {
        switch (answer){
            case "option 1":
                //action 1;
                break;
            case "exit option":
            	//previous action
            	return rl.close();
            default:
                //default action
        }
        program();
    });
}

program();
app.get('/:id/tracker.png', function(request, response, next) {
    var emailId = request.param.id;
    var buf = new Buffer([
        0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00,
        0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x2c,
        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
        0x02, 0x44, 0x01, 0x00, 0x3b
    ]);
    response.set('Content-Type', 'image/png');
    response.end(buf, 'binary');
    db.findOne({ id: emailId }, function(error, email) {
        if(error) return next(error);
        app.emit('event:opened', email);
    });
});

app.on('event:opened', function(email) {
    console.log('Email was opened');
    console.log(email.to);
    console.log(email.subject);
});
The following examples illustrate defining simple routes.

Respond with Hello World! on the homepage:
//get method for retrieving data.
app.get('/', function (req, res) {
  res.send('Hello World!')
})
 Save
Respond to POST request on the root route (/), the application’s home page:
//send method for sending data.
app.post('/', function (req, res) {
  res.send('Got a POST request')
})
 Save
Respond to a PUT request to the /user route:
//put request to 
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})
 Save
Respond to a DELETE request to the /user route:

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})
Basic routing
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)
 Save
Where:

app is an instance of express.
METHOD is an HTTP request method, in lowercase.
PATH is a path on the server.
HANDLER is the function executed when the route is matched.
function processSQLFile(fileName) {

  // Extract SQL queries from files. Assumes no ';' in the fileNames
  var queries = fs.readFileSync(fileName).toString()
    .replace(/(\r\n|\n|\r)/gm," ") // remove newlines
    .replace(/\s+/g, ' ') // excess white space
    .split(";") // split into all statements
    .map(Function.prototype.call, String.prototype.trim)
    .filter(function(el) {return el.length != 0}); // remove any empty ones

  // Execute each SQL query sequentially
  queries.forEach(function(query) {
    batch.push(function(done) {
      if (query.indexOf("COPY") === 0) { // COPY - needs special treatment
        var regexp = /COPY\ (.*)\ FROM\ (.*)\ DELIMITERS/gmi;
        var matches = regexp.exec(query);
        var table = matches[1];
        var fileName = matches[2];
        var copyString = "COPY " + table + " FROM STDIN DELIMITERS ',' CSV HEADER";
        var stream = client.copyFrom(copyString);
        stream.on('close', function () {
          done();
        });
        var csvFile = __dirname + '/' + fileName;
        var str = fs.readFileSync(csvFile);
        stream.write(str);
        stream.end();
      } else { // Other queries don't need special treatment
        client.query(query, function(result) {
          done();
        });
      }
    });
  });
}
const port = process.env.PORT || 3000;

import express from "express";
import path from "path";
import bodyParser from "body-parser";
import cors from "cors";
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

//* Root Handler
app.get("/", (req, res) =>
  res.sendFile(path.join(__dirname + "/public/index.html"))
);

app.get('api/v1', (req,res) => res.json())

// Set static folder
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api/v1', require('./routes/api/v1'))

app.listen(port, () => {
  console.log(`Server at: http://localhost:${port}`);
});
command line

npm init -y (creates the package for dependencies)

npm i [module]  (creates dependency key and module repository)
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      // "processId": "${command:PickProcess}",
      "protocol": "inspector",
      "restart": true,
      "name": "Launch Programa",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}
// BASH
mkdir src
mkdir build
touch src/index.ts
touch .gitignore
touch README.md
tsc -y
npm init -y
npm install nodemon concurrently @types/express --save-dev

// package.json
...
"scripts": {
  "start:build": "tsc -w",
  "start:run": "nodemon ./build/index.js",
  "start": "concurrently npm:start:*"
},
...

// tsconfig.json
...
"outDir": "./build",
"rootDir": "./src",
...

// .gitignore
node_modules
*.env

// README.md
### Start
```bash
npm run start
```

// src/index.ts
import express from 'express'
const port = 3000
const app = express()

console.log("Hello, World!!!")

logSomething("This is a string that I'm logging")

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');

fs.mkdirSync(dirPath);
router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
const express = require('express')
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLNonNull
} = require('graphql')
const app = express()
const port = 3000

// Sample Data
const authors = [
	{ id: 1, name: 'Dan Brown' },
	{ id: 2, name: 'J. R. R. Tolkien' },
	{ id: 3, name: 'Brent Weeks' }
]

const books = [
	{ id: 1, name: 'The Lost Symbol', authorId: 1 },
	{ id: 2, name: 'Angels and Demons', authorId: 1 },
	{ id: 3, name: 'The Davinci Code', authorId: 1 },
	{ id: 4, name: 'The Fellowship of the Ring', authorId: 2 },
	{ id: 5, name: 'The Two Towers', authorId: 2 },
	{ id: 6, name: 'The Return of the King', authorId: 2 },
	{ id: 7, name: 'The Way of Shadows', authorId: 3 },
	{ id: 8, name: 'Beyond the Shadows', authorId: 3 }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  description: 'This represents a book written by an author',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
    authorId: { type: GraphQLNonNull(GraphQLInt) },
    author: {
      type: AuthorType, // AuthorType is defined below the same way that BookType is defined above
      resolve: (book) => {
        return authors.find(author => author.id === book.authorId)
      }
    }
  })
})

const AuthorType = new GraphQLObjectType({
  name: 'Author',
  description: 'This represents the author of a book',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) }
  })
})

const RootQueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'Root Query',
  fields: () => ({
    books: {
      type: new GraphQLList(BookType),
      description: "List of books",
      resolve: () => books
    }
  })
})

const schema = new GraphQLSchema({
  query: RootQueryType
})



app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))


app.get('/', (req, res) => {
  res.send(`<a href="http://localhost:${port}/graphql">GraphiQL</a>`)
})

// QUERY:
// 
// {
// 	books {
//     id
//   	name
//     author {
//       name
//     }
// 	}
// }

// RESULT
// 
// {
//   "data": {
//     "books": [
//       {
//         "id": 1,
//         "name": "The Lost Symbol",
//         "author": {
//           "name": "Dan Brown"
//         }
//       },
//       {
//         "id": 2,
//         "name": "Angels and Demons",
//         "author": {
//           "name": "Dan Brown"
//         }
//       }, //...
//     ]
//   }
// }

app.listen(port, () => {
  console.log(`App listening on http://localhost:${port}`)
});
$ sudo npm install --global cross-env
var express = require('express');
var app = express();

app.enable('trust proxy'); //to detect if req.secure is true/false

//Block http requests. Only allow https requests
app.use(function (req, res, next) {
	if (req.headers['x-forwarded-proto'] !== 'https'){
      return res.status(404).send('Not found');
    } else {
    next();
    }
})

exports = module.exports = app;
router.get("/search/:page", (req, res, next) => {
  const resultsPerPage = 5;
  const page = req.params.page >= 1 ? req.params.page : 1;
  const query = req.query.search;

  Product.find({ name: query })
    .select("name")
    .sort({ name: "asc" })
    .limit(resultsPerPage)
    .skip(resultsPerPage * page)
    .then((results) => {
      return res.status(200).send(results);
    })
    .catch((err) => {
      return res.status(500).send(err);
    });
});
userSchema.pre('save', async function(next){
    if (!this.isModified('password')) return next()
    this.password = await bcrypt.hash(this.password, 8)

    next()
})
//You must require fs and path before this action can be done
//set this on the top of the model
const imagePath = 'uploads/image'


//Create a virtual with the schema name e.g.
blogSchema.virual('imagePath').get(function(){
if(this.image != null){
return path.join('/', imagePath, this.image)
}
})

//exports the imagePath as like this
module.exports.imagePath = imagePath 


//go to the route and require it with the model name e.g.
const uploadPath = path.join("public", BlogModel.imagePath);

//set your function for unlink and call it on the delete route
function removeImage(image){
	fs.unlink(uploadPath, image), (err)=>{
    if(err) console.log(err)
    })
}

// Let generalize user data
app.use((req, res, next) => {
    res.locals.user = req.isAuthenticated() ? req.user : null
    return next()
})
const passport = require('passport')
const LocalStrategy = require("passport-local").Strategy;

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done)=>{
    try{    
    const user = await User.findOne({ email })
        if (!user) return done(null, false, { message: 'User not exists' })
        if (!await user.checkPassword(password)) return done(null, false, { message: 'Incorrect Password' })
        return done(null, user)
    } catch (e) {
        
        return done(e)
    }
}
))

passport.serializeUser((user, done)=>{
    return done(null, user._id)
})

passport.deserializeUser(async (_id, done) => {
    try {
        const user = await User.findOne({ _id })
        return done(null, user)
    } catch (e) {
        return done(e)
    }
})





//place this one on the route
router.post('/login', (req, res, next) => {
  console.log(req.body.email)
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: 'Login failed'
          }
      }
      return res.redirect('/user/login')
      }
    // Let check for user
    if (!user) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: info.message
        }
      }
      return res.redirect('/user/login')
    }
    req.logIn(user, (err) => {
      if (err) {
        req.session.flashData = {
          message: {
            type: 'error',
            body: 'Login failed'
          }
        }
      }
      return res.redirect('/task/viewtask')
    })
  })(req, res, next)
})


//place this on index.js

// For Passport to work with session
app.use(passport.initialize());
app.use(passport.session());
const flashMsg = (req, res, next) => {
    if (req.session.flashData) {
        for (const key in req.session.flashData) {
            res.locals[key] = req.session.flashData[key]
        }

        req.session.flashData = null
    }
     
    next()
}

module.exports = flashMsg
const mongooseValidation = (theError) => {
    const errors = {}
    const details = errors.theError
    for (const key in details)
    {
        errors[key] = [details[key].message]
    }
    return errors
}

module.exports = mongooseValidation
var {src, dest, watch}        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');

// Static server
  function bs() {
    serveSass();
  browserSync.init({
      server: {
          baseDir: "./"
      }
  });
  watch("./*.html").on('change', browserSync.reload);
  watch("./scss/**/*.scss", serveSass);
  watch("./js/*.js").on('change', browserSync.reload);
};

// Compile sass into CSS & auto-inject into browsers
 function serveSass() {
  return src("./scss/*.scss")
      .pipe(sass())
      .pipe(dest("./css"))
      .pipe(browserSync.stream());
};

exports.serve = bs;
var fs = require('fs');

fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
var stripe = require('stripe')('sk_test_LIPsyf7cwBv0pbWPbzjeqAhj009wgDByN7');

stripe.customers.create(
  {
    description: 'My First Test Customer (created for API docs)',
  },
  function(err, customer) {
    // asynchronously called
  }
);
var express = require("express");
var app = express();
const session = require('express-session');
var MemcachedStore = require('connect-memjs')(session);

// configure sessions
var store = new MemcachedStore({servers: [process.env.MEMCACHEDCLOUD_SERVERS], username: process.env.MEMCACHEDCLOUD_USERNAME, password: process.env.MEMCACHEDCLOUD_PASSWORD});
app.use(session({ secret: 'keyboard cat',
   resave: true,
   saveUninitialized: true,
   cookie: { secure: true }, 
   store: store
}))
                                exports.removeById = (req, res) => {
   UserModel.removeById(req.params.userId)
       .then((result)=>{
           res.status(204).send({});
       });
};

                                
                                var app = express()
var sess = {
  secret: 'keyboard cat',
  cookie: {}
}
 
if (app.get('env') === 'production') {
  app.set('trust proxy', 1) // trust first proxy
  sess.cookie.secure = true // serve secure cookies
}
 
app.use(session(sess))
                                
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function (result) {
       alert("The result is "+result);
	}
});
                                
<form action="/new" method="post">

  <input name="title" type="text">
  <input name="description" type="text">
  <input name="steps[0][text]" type="text">
  <input name="steps[0][ingredients]" type="text">
  <input name="steps[1][text]" type="text">
  <input name="steps[1][ingredients]" type="text">
  <button type="submit">Submit Form</button>

</form>
const songs[];
const results;

for (var i, i++, i<songs.length){
    if(song[i].artist == "Drake"){
      result.push(songs[i]);
    };

// OR

const songs [];
const result = songs.filter ( song => song.artist == "Drake");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var slug = require('mongoose-slug-generator');

mongoose.plugin(slug);

const pageSchema = new Schema({
    title: { type: String , required: true},
    slug: { type: String, slug: "title" }
});

var Page = mongoose.model('Page', pageSchema);
module.exports = Page;
router.post('/:id/edit', auth.requireLogin, (req, res, next) => {
  Post.findByIdAndUpdate(req.params.id, req.body, function(err, post) {
    if(err) { console.error(err) };

     res.redirect(`/`+req.params.id);
  });
});
$ git status 
$ git add .
$ git commit -m "update information"
$ git push heroku master
$ git heroku open
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
    title: { type: String , required: true},
    content: [{type: String}]
});


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
star

Sat May 08 2021 07:38:30 GMT+0000 (UTC)

#javascript #nodejs
star

Tue Apr 27 2021 22:51:13 GMT+0000 (UTC) wrote it myself

#nodejs
star

Wed Apr 21 2021 09:13:13 GMT+0000 (UTC)

#nodejs #vue.js #react.js
star

Wed Mar 31 2021 12:07:26 GMT+0000 (UTC)

#nodejs #mongoose
star

Mon Mar 15 2021 13:40:38 GMT+0000 (UTC) https://github.com/mattdesl/gsx-pdf-optimize

#nodejs #commandline #npx
star

Thu Mar 11 2021 13:05:11 GMT+0000 (UTC)

#nodejs
star

Tue Mar 09 2021 15:29:16 GMT+0000 (UTC)

#nodejs
star

Wed Feb 24 2021 20:46:20 GMT+0000 (UTC) https://www.npmjs.com/package/ip

#nodejs #javascript
star

Sat Feb 06 2021 12:27:05 GMT+0000 (UTC)

#javascript #nodejs
star

Thu Jan 07 2021 22:05:21 GMT+0000 (UTC) https://www.reddit.com/r/node/comments/4txqqw/how_to_track_email_opens_with_nodejs_app/

#nodejs #javascript #email
star

Fri Dec 04 2020 01:43:47 GMT+0000 (UTC)

#nodejs,jquery #nodejs
star

Fri Dec 04 2020 01:42:13 GMT+0000 (UTC)

#nodejs #jquery
star

Fri Nov 27 2020 18:42:18 GMT+0000 (UTC) https://stackoverflow.com/questions/22636388/import-sql-file-in-node-js-and-execute-against-postgresql

#sql #nodejs
star

Sun Nov 22 2020 16:49:47 GMT+0000 (UTC) debtcollect.io

#typescript #nodejs
star

Sat Nov 14 2020 17:51:41 GMT+0000 (UTC)

#nodejs
star

Wed Nov 11 2020 12:56:36 GMT+0000 (UTC)

#json #nodejs #debug
star

Wed Nov 04 2020 18:12:52 GMT+0000 (UTC) https://www.digitalocean.com/community/tutorials/nodejs-how-to-use__dirname

#javascript #nodejs
star

Sat Oct 10 2020 17:41:42 GMT+0000 (UTC) https://stackoverflow.com/questions/61056021/improve-mongoose-validation-error-handling

#javascript #nodejs #mongoose
star

Fri Oct 09 2020 23:22:52 GMT+0000 (UTC) https://github.com/716green/graphql-express-setup/blob/main/server.js

#nodejs #javascript #graphql #express
star

Sun Oct 04 2020 06:48:54 GMT+0000 (UTC)

#nodejs
star

Wed Aug 26 2020 21:29:30 GMT+0000 (UTC)

#nodejs #javascript
star

Sat Aug 22 2020 23:06:10 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 16:22:15 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 16:18:23 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 15:53:41 GMT+0000 (UTC)

#nodejs #javascript
star

Mon Aug 17 2020 15:51:22 GMT+0000 (UTC)

#nodejs #javascript
star

Tue Aug 04 2020 22:56:30 GMT+0000 (UTC) https://flaviocopes.com/node-mass-rename-files/

#javascript #nodejs
star

Mon Jun 29 2020 22:48:29 GMT+0000 (UTC)

#gulp #nodejs
star

Mon Jun 08 2020 10:15:25 GMT+0000 (UTC) https://lavalite.org/blog/fastest-method-to-copy-file-in-nodejs

#nodejs #fs #javascript
star

Mon May 25 2020 10:06:38 GMT+0000 (UTC) https://stripe.com/docs/api/customers/create

#nodejs
star

Thu Apr 30 2020 06:35:49 GMT+0000 (UTC) https://www.toptal.com/nodejs/secure-rest-api-in-nodejs

#nodejs
star

Tue Apr 28 2020 19:40:32 GMT+0000 (UTC) https://medium.com/javascript-in-plain-english/querying-sql-server-in-node-js-using-async-await-5cb68acf2144

#javascript #nodejs
star

Tue Apr 28 2020 19:22:18 GMT+0000 (UTC) https://www.npmjs.com/package/express-session

#nodejs
star

Sun Apr 26 2020 20:50:22 GMT+0000 (UTC) https://api.jquery.com/jquery.post/

#javascript #nodejs
star

Sun Mar 29 2020 07:06:35 GMT+0000 (UTC) https://gist.github.com/trantorLiu/5924389

#javascript #nodejs #handlebars #express
star

https://docs.mongodb.com/manual/reference/operator/update/push/

#javascript #nodejs
star

https://medium.com/@thiscodeworks.com/how-to-redirect-your-node-js-app-hosted-on-heroku-from-http-to-https-50ef80130bff

#javascript #nodejs #commandline

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension