Complete Node.js Developer Course (Udemy by Andrew Mead)

¡Supera tus tareas y exámenes ahora con Quizwiz!

What is an ODM used for?

ODM provides a simple API for CRUD database operations as well a performing data validation.

What is ODM in web development?

Object Data Mapper

What HTTP operation (GET, POST, ..., etc.) is commonly used for updating?

PATCH

What is promise chaining?

Promise chaining allows for processing more than one asynchronous tasks. It's a way to avoid nesting promise code which creates unneeded complexity.

What is a popular tool for Mongo DB management?

Robo 3T

What's a clear way to respond to that a create request succeeded and something was created?

Send a 201, 'Created', status code in the response instead of just 200.

How to change the code from getting all documents to one document in a collection?

... app.get('./tasks/:id', (req, res) => { const _id = req.params.id Task.findById(_id).then((task) => { if(!task) { res.status(500).send() } res.send(task) })... ... })

How to read a single document from a MongoDB collection?

... // inside the connect callback which provides client db.collection('users').findOne({ name: 'Jen', age: 1, }, (error, user) => { if(error) { return console.log('Unable to insert tasks.') } console.log(user) })

How to insert one document into a MongoDB collection?

... // inside the connect callback which provides client const db = client.db(databaseName) db.collection('users').insertOne({ _id: id, name: 'Vikram', age: 26, }, (error, result) => { if(error) { return console.log('Unable to insert user.') } console.log(result.ops) })

Show sample code for a promise.

// Sample code with resolve behavior commented out const doWorkPromise = new Promise((resolve, reject) => { setTimeout(() => { // resolve([ 7, 4, 1 ]) reject('Things went wrong!') }, 2000) }) doWorkPromise.then((result) => { console.log('Success!', result) }).catch((error) => { console.log('Error: ', error) })

How is 'debugger' used from the console?

1) Add a 'debugger' statement to code. 2) Run Node.js app with 'node inspect ...' 3) Browse to link provided by node, or go to chrome://inspect in Chrome.

What are the 3 parts of an HTTP request?

1) Request line 2) Request headers 3) Request body

What is a GUID and how does MongoDB use it?

A GUID is a globally unique identifier. MongoDB uses this as the id for each document. These id's are unique across databases and allow MongoDB to scale database(s) across multiple host and/or clusters.

What does the Node.js event loop do?

Event loop waits for the call stack to be empty and then pushes the next available function from the callback queue to be pushed onto the call stack.

What is Express in relation to Node.js?

Express.js is an npm package which lets us create a web server with Node.js. It's a web framework.

How does promise chaining work?

Instead of nesting a promise in a promise, for example: func(x, y).then((args) => { func(x, args).then(...).catch(...) }).catch(...) Where func is defined to return a Promise, we have the then clause return a Promise object: func(x, y).then((args, y) => { ... return func(args, y) }).then((finalargs) => { ... }) .catch(...)

How to connect to a MongoDB with Mongoose?

const mongoose = require('mongoose') ... mongoose.connect('mongodb://127.0.0.1:27017/task-manager-api', { useNewUrlParser: true, useUnifiedTopoloty: true, useCreateIndex: true, }

How to connect to a local MongoDB?

const { MongoClient } = require('mongodb') const connectURL = 'mongodb://127.0.0.1:27017' MongoClient.connect(connectURL, { useNewUrlParser: true}, (error, client) => { if(error) { return console.log('Unable to connect to datbase.') } ... )}

How is a GUID created in Node.js?

const { MongoClient, ObjectID } = require('mongodb') const id = new ObjectID() console.log(id) console.log(id.getTimestamp())

How to find one or more documents matching our filter criteria?

db.collection('tasks').find({ completed: false }).toArray((error, tasks) => { if(error) { return console.log('Unable to find tasks.') } console.log(tasks) })

Show a MongoDB call to update a document using a promise.

db.collection('users').updateOne({ name: 'Mike' }, { $inc: { age: 1 } }).then((result) => { console.log(result) }).catch((error) => { console.log(error) })

What is V8 or the V8 JavaScript engine?

"V8 is Google's open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in Node.js, among others. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. V8 can run standalone, or can be embedded into any C++ application." (v8.dev)

After NPM initialization, how are NPM modules installed?

'npm i <module name> -y'

What is 'setTimeOut()' in a Node.js script?

'setTimeOut()' is a function which is provided by the Node API. It is not native to JavaScript and is not implemented in the V8 JavaScript engine. It is implemented in C++ by Node.js. The Node API provides a way for this functionality to be called from JavaScript via the Node API. 'setTimeOut()' registers an event to be called by the Node API's.

What is a promise in JavaScript?

A promise is a mechanism in JavaScript to handle asynchronous behavior. It's considered better than using callbacks, which is now considered deprecated. Promises provide cleaner code and guarantee success/failure (resolve, reject) code is only called once.

What do the MongoDB functions return when a callback is not passed?

A promise object on which then() and catch() can be called.

What do async functions do and how are they defined?

Async functions always return a promise and are defined as: const func = async () => {}

What is Async/Await in JavaScript?

Async/Await aid in code management of asynchronous code with callbacks and promises. It is typically used with every route handler.

How does async/await affect closure/variable scoping/access?

Async/await allows for the caller of await functions to call them from the same scope so variables in this scope can be passed to await functions: const doWork = async () => { const sum = await add(1, 99) const sum2 = await add(sum, 50) const sum3 = await add(sum2, 3) return sum3 }

Where is async/await particularly beneficial? Provide an example.

Async/await are particularly beneficial in writing clean code when handling routes with ExpressJS. It removes the clutter of then and catch with promises. For example: app.get('/tasks', async (req, res) => { try { res.send(await Task.find({})) } catch(e) { res.status(500).send(e) } })

What does await do and provide an example?

Await indicates to call an asynchronous function and wait for it to finish returning it's value: const s = await func(...) This is easier syntax and less confusing than promise chaining.

What is a common REST API structure for CRUD (create, read, update and delete?

Create: POST /<path> Read all: GET /<path> Read one: GET /<path>/:id Update one: PATCH /<path>/:id Delete one: DELETE /<path>/:id

How to launch Mongo DB from the Windows 10 CLI assuming the EXE is in D:\Users\godescbach\mongodb\bin using D:\Users\godescbach\mongodb-data as the path to the database?

D:\Users\godescbach\mongodb\bin\mongod.exe --dbpath=D:\Users\godescbach\mongodb-data

How to use Mongoose middleware.

Define a schema object, userSchema = mongoose.Schema(...), then use pre(), post() and other functions on the Schema object, userSchema, which takes the specified action. For example: userSchema.pre('save', async function (next) { const user = this if(user.isModified('password')) { user.password = await bcrypt.hash(user.password, 8) } console.log('just before saving') next() })

What are popular ODM and validation packaged for Node.js?

For ODM, mongoose and for validation, validator.

How do we access an NPM module installed in JavaScript?

For the request module, as an example: "const request = require('request')" the use 'request'.

How to setup node to use nodemon when starting application for development?`

In ./package.json: ... "scripts": { ... "dev": "nodemon src/index.js" }, ...

How to setup node to start when started by an cloud application platform such as Heroku?

In ./package.json: ... "scripts": { ... "start": "node src/index.js" }, ...

Where should data models such as Mongoose data models be kept?

In a separate models directory, on model per file.

How do we initialize our Node.js app to use NPM modules?

In the application source file directory, run 'npm init -y'.

How to connect to Mongo DB from the express.js file, e.g. index.js?

Include the statement "require('./db./mongoose')" where ./db./mongoose.js contains the connect statement: ... const mongoose = require('mongoose') mongoose.connect('mongodb://127.0.0.1:27017/task-manager-api', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }) ...

What is object destructuring in JavaScript?

It's a shorthand for declaring variables for properties of an object in subsequent code. 'const { var1, var2 } = data' is the same as " const var1 = data.var1 const var2 = data.var2 ". This can also be uses in parameters, so func(data) becomes func({var1, var2}).

When using the https frrom nodejs rather then requests from npm, what functions are used to perform an HTTP(s) request?

Low-level function calls such as r = https.request() and r.on('data'), r.on('end'), r.on('error') and r.end().

Is Node.js single-threaded?

No. There is a single thread for executing JavaScript. However, there are other threads tracking asynchronous event.

Are any functions in the callback queue run before main() finishes?

No. While main() is on the call stack, no callback functions will run.

What is the callback queue?

This is a queue of callback functions which were registered for callback via the Node API.

How do we get a collection's documents using ExpressJS and MongooseJS?

To get all tasks from the collection 'tasks': const express = require('express') const Task = require('./models/task') // model def. const app = express() const port = process.env.PORT || 3000 app.use(express.json()) app.get('/tasks', (req, res) => { Task.find({}).then((tasks) => { res.send(tasks) }).catch((error) => { res.status(500).send(error) }) })

What is the callback pattern?

To get values from an asynchronous callback function like setTimeout(), wrap the asynchronous callback function with a function that takes a callback function as an argument. Then have the asynchronous function's unnamed callback call the callback function passed as a parameter. E.g.: const add = (x, y, callback) => { setTimeout(() => { callback(x + y) }, 2000) } add(1, 4, (sum) => { console.log(sum) // Should print: 5 })

How are promises typically used?

Typically, promises are implemented in a library/packages we're using like MongoDB.

How to insert functionality on a MongoDb action, such as update, w/o changing the handler/router JS code?

Use Mongoose model middleware.

How to insert many documents into a MongoDB collection?

Use insertMany() passing a collection, [ ... ], instead of a single object as was used in inertOne().

How to get the binary (buffer) representation of an object id?

Use the id data member, ObjectId().id, or id.id from the id object from id = new ObjectId().

How to get the string representation of an object id (in hex)?

Use the toHexString() member function, id.toHexString, or ObjectId().toHexString().

How does express send a response to a GET request?

Using res.send(...) inside app.get() callback.

What is the property shorthand in JavaScript?

When the name of the lhs and rhs are the same in a property, only the name is needed. E.g. { url: url } become { url }.

How to set the status code in an HTTP response from within an Express JS request (GET, POST, ..., etc.)?

Where app = express() and, for example, the request is app.request(path, (req, res) => {}) then use res.status(n) where n is the HTTP status to send back.

How to setup routes for users using express.js?

Where app = express(), express provides app.get(), app.post(), app.delete() and app.patch() methods.

How to tell express.js to parse incoming JSON parameters?

Where app = express(), use app.use(express.json())

In Express, how do we handle GET requests to a specific route (e.g. /, /help, /about, ..., etc.)?

app.get('<route>', (req, res) => {})

What are 4 terms often associated with Node.js

asynchronous i/o, non-blocking, single-threaded & event driven

What is a popular npm tool for hashing passwords?

bcryptjs

Show an sample Mongoose User model using validation.

const User = mongoose.model('User', { name: { type: String, required: true, trim: true, }, email: { type: String, required: true, trim: true, lowercase: true, validate(value) { if (!validator.isEmail(value)) { throw new Error('Email is invalid.') } } }, age: { type: Number, default: 0, validate(value) { if (value < 0) { throw new Error('Age must be > 0.') } } }, password: { type: String, required: true, trim: true, validate(value) { if (!validator.isLength(value, { min: 6, max: undefined }) ) { throw new Error('Length must be 6 or more characters.') } if(value.toLowerCase().includes('password')) { throw new Error('Cannot contain the word "password".') } } } })

Show an example of adding a user defined by the Mongoose model 'User' to a Mongo db collection.

const User = require('./models/user') app.use(express.json()) app.post('/users', (req, res) => { const user = new User(req.body) user.save(). then(() => { res.send(user) }).catch((error) => { res.status(400).send(error) }) })

How do we start a web-server listening on port 3000 in Express?

const app = express() app.listen(3000, () => {// code run after server starts})

Give an example of using bcryptjs.

const bcrypt = require('bcryptjs') const myFunction = async () => { const password = 'Red12345!' const hashedPassword = await bcrypt.hash(password, 8) console.log(password) console.log(hashedPassword) const isMatch = await bcrypt.compare('red12345!', hashedPassword) console.log(isMatch) } myFunction()

Show code for setting a simple express server?

const express = require('express') const app = express() const port = process.env.PORT || 3000 app.listen(port, () => { console.log('Server is up on port ' + port) })

What's a good website for HTTP statuses?

httpstatuses.com

What MongoDB functions are used for CRUD operations?

insertOne(), insertMany(), findOne(), find(), updateOne(), updateMany(), deleteOne(), deleteMany()

How to install nodemon as a development dependency?

npm i nodemon@<latest version> --save-dev

How to use the dev start script to start nodemon?

npm run dev

What is a popular NPM module used for client REST API calls?

request

Show an example of a REST API call using request.

request({ url: url }, (error, response) => { const data = JSON.parse(response.body) console.log(response.body) })

What is a simple Node.js function illustrating its asynchronous capabilities?

setTimeout(() => { console.log('2 second timer') }, 2000)


Conjuntos de estudio relacionados

Biology Ch 8 Photosynthesis Study Guide

View Set

(Workbook) CHP 12: Private On Site Wastewater

View Set

Accy 405 - Chapter 3: Tax Formula and Tax Determination; An Overview of Property Transactions

View Set