JS.Node Flashcards

1
Q

What is a common error made when storing data as JSON ?

A

stringifying the data more than once before storage or not stringifying it at all.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what does array.filter() do?

A

filters an existing array and returns a new array that contains only the filtered values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what does array.foreach() do?

A

Much like a for loop, it loops through each item in an array and performs a specified opperation on each item.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does array.map() do?

A

Performs an opperation on each value within an array and returns a new array that contains the new mapped values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does array.reduce() do?

A

reduces the values in a given array to a single value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does it mean when we say that node uses “non-blocking I/O”?

A

It means that Node is asynchronous.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the two most common JSON commands?

A

JSON.stringify() and JSON.parse()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does JSON.stringify do?

A

turns an object into a JSON object by adding double quotes to the keys and values in objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does JSON.parse() do?

A

turns JSON objects into objects by removing the double quotes from the keys in an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which module is used to work with files in node?

A

fs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which module is used to provide colourful feedback in the console?

A

chalk

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does the V8 engine works

A

Node itself is written in C++ and the V8 engine is embedded into it. When writing javascript. The javascript and it’s c++ bindings are passed into the V8 engine which converts it to machine language which can be run on a machine like a computer or a server.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

The javascript engine used by Chrome

A

V8

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

The javascript engine used by Edge

A

Chakra

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

The javascript engine used by Firefox

A

Spidermonkey

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

The javascript engine used by Edge

A

Javascriptcore

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a javascript engine?

A

A program that compiles javascript down to machine language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the difference between an AOT and JIT compiler?

A

AOT (ahead of time) compilers, will compile the entire program into machine code ahead of time.

JIT (Just in time) compilers used a combination of interpretation and compilation and will compile blocks of code just before it is neede.

JIT is slower than AOT but it makes it easier to debug and maintain code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

The V8 engine is multi-threaded. What are the 4 main threads and what are there functions?

A
  1. Main thread: Fetch - compile -execute
  2. Compiler thread: Codegen(ignition): converts to
    machine code Crankshaft(turbofan): optimizes hot
    code
  3. Profiler thread: Monitors code and finds “hot” sections
  4. Garbage collection thread: Garbage collection
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does crankshaft optimize code?

A
1. inlining: All the function in the "hot" path are replaced 
   by the actual code from the function to improve 
   performance
2. Hidden classes: The compiler generates hidden 
    classes that maintains the pointers to every object 
    property in a class structure so that it need not be 
    looked up everytime
3. inline caching: A cache of the object type that is most 
    likely to be passed to a function is maintained so that 
    unnecessary lookups are avoided
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

what is a “method”?

A

Methods are functions defined as a propertie of an object or class. methods are executed using the dot notation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Why are arrow functions not well suited for use as methods in an object?

A

Because arrow functions do not bind their own “this” value, instead they access the “this” value of the context they were created in. This can make it difficult to access properties within objects. Instead it would be better to use an anonymous function which binds its own “this” value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are arrow functions best used for?

A

callback functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What should we use in the place of array.filter() when looking for a single item in a large array? Why?

A

Array.find()

Array.filter() will look through each item in a list one at a time. It will continue to do so even if the item we are looking for has been found.

Example. In a list of 1000 items, if the item we are looking for is at index 89, it will continue to look through the remaining 911 items before stopping.

Array.find() will stop after it finds the first instance of the desired item.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Array.find()

A

Looks for item in an array an returns the item (not new array) when found.

Returns “undefined” when nothing is found

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How can I use chrome as a debugging tool?

A

add debugger to script
run “node inspect app.js commands” in terminal
navigate to chrome://inspect in the chrome browser
add folders to project
press esc to toggle console
press run top right hand corner
look at values in the right hand pane.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are the 6 catagories of errors in javascript?

A

EvalError: Raised when the eval() functions is used in an incorrect manner.

RangeError: Raised when a numeric variable exceeds its allowed range.

ReferenceError: Raised when an invalid reference is used. Like when you use a variable that has not been declared

SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.

TypeError: Raised when the type of a variable is not as expected. Like when you call .toUpperCase() on an integer

URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Javascript generates an error object when an error occurs. Which two propperties does it contain?

A

name

message

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is a stack trace?

A

A stack trace is a list of the functions, in order, that lead to a given point in a software program.A stack trace is essentially a breadcrumb trail for your software.It helps us understand the steps that lead to the error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is the biggest problem with anonymous functions?

A

They make it difficult to debug as they show up in the stack trace as anonymous.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

console.trace()

A

A command that can be placed inside a function which then generates a stack trace for that funciton in the console or terminal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Format of a stack trace

A
Error name
    function name, file, line number, column number
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Which async function can be used to time the execution of a function?

A

setTimeout(callback, time in milliseconds)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Call stack

A

a call stack is a stack data structure which is based on the LIFO or last in first out principle. It uses four opperations namely push (to add data), pop (to remove data), peek (to return the value of the top item), isEmpty (returns true if stack is empty). Stacks emulate real life stacks like a stack of books or a can of tennis balls.

Whe a script runs, it wraps all of the code in the main() function. The main function gets pusched onto the call stack and executes, then any function called by main gets pushed onto the call stack on top of main. when the function has finished running it is poped of the call stack. and right at the end of the script the main funciton is popped of the stack.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Callback que

A

a que used by node to keep track of callback functions that are waiting to run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Event loop

A

Adds functions waiting in the call back cue to the call stack when the stack is empty.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Explain what happens in the background when running asyncronous scripts?

A

Function gets pushed onto the callstack, the async event gets registered with the node api, when it is ready or complete it is moved to the callback cue where it waits for the event loop to add it to the call stack as soon as the call stack is empty. Once it is in the call stack it get executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How to initialize a new project as an NPM project?

A

run “npm init -y” in the root of the folder

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

package.json file

A

holds the metadata and information about dependencies and project configuration. It is generated automatically as soon as a project is initialized using npm init

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Which npm module can be used ot make http requests?

A

request

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

simplest way to make an http request using request?

A

request({url:url,json:true},(error,response)=>{
console.log(response)
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Which chrome extension presents json data in a more readable format?

A

JSON formatter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What are query strings?

A

a query string is the part of a uniform resource locator (URL) which assigns values to specified parameters. The query string commonly includes fields added to a base URL

query string format base_url?key=value&key=value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Which api provides geocoding or location based information?

A

Mapbox.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

How can errors be handled when using the npm request module to make http requests?

A
if(error){
    console.log("cannot connect)
}else if(response.body.error){
    console.log("cannot find info")
}else{
    console.log(response.body)
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is defensive programming?

A

Anticipating possible errors and pre-emptively writing code that solves the anticipated problem

A common example is the try/catch statements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What is a call back function?

A

A callback is a function that is to be executed after another function has finished executing

Functions that do this are called higher-order functions.

Any function that is passed as an argument is called a callback function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is a higher order function?

A

Any function that calls another function or that takes another funciton as an argument

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What is a common convention used for callback functions?

A

someFunction(arg,(error,data)=>{

})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

which function helps to parse user input into a valid URI component?

A

encodeURIComponent()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

In which folder should code be placed that make api calls or HTTP requests?

A

utils

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is callback chaining?

A

chaining together a number of functions via callbacks while passing arguments (data) between them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is callback hell?

A

When so many functions have been chained together that it becomes unreadable and difficult to understand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What is object destructuring?

A

A method that extracts values from an object

const book = {
label:"To the moon and back",
price:56,
author:"Ryan holiday"
}

const {label, price} = book

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

How to rename a property during object destructuring?

A

currentName:newName

const book = {
label:"To the moon and back",
price:56,
author:"Ryan holiday"
}

const {label:title, price:cost} = book

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How to set defualt values for properties when they don’t exist in an object during destructuring?

A

Using the assignment operator

const book = {
label:"To the moon and back",
price:56,
author:"Ryan holiday"
}

const {title, cost = 100} = book

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

How to destructure an object passed in as an argument into a function?

A

by using curly braces.

const book = {
label:"To the moon and back",
price:56,
author:"Ryan holiday"
}
function inventory(type, {label, price, author}){
    some code here
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Which core modules are used ot make http requests

A

http and https

59
Q

How to make an HTTP request using the https core module?

A

const https = require(‘https’);

const request = https.request(url,(response)=>{
    let data = '';
    //event listener that adds the chunks of data returned 
      from the server. Data is returned as a series of buffers 
      which needs to be converted to a string
    response.on('data', (chunk)=>{
        data =  data + chunk.toString()
});
    //runs when response is complete converting the 
      string to an object
    response.on('end',(chunk)=>{
        const body = JSON.parse(data);
        console.log(body)
})

});

//Event listener that handles errors
request.on('error', (error)=>{
    console.log('An error ', error)
});
//This code snippet tells the request to run, it won't run without it. 
request.end();
60
Q

Which npm module is commonly used to create servers?

A

express

61
Q

directory structure for node projects

A

lib/ is intended for code that can run as-is

src/ is intended for code that needs to be manipulated before it can be used

build/ is for any scripts or tooling needed to build your project

dist/ is for compiled modules that can be used with other systems.

bin/ is for any executable scripts, or compiled binaries used with, or built from your module.

test/ is for all of your project/module’s test scripts
unit/ is a sub-directory for unit tests

integration/ is a sub-directory for integration tests
env/ is for any environment that’s needed for testing

62
Q

What is the src directory intended for?

A

is intended for code that needs to be manipulated before it can be used

63
Q

What is the most basic server setup using express?

A

const express = require(‘express’); //import express

const server = express(); //create a server

server.get(‘’,(req,res)=>{ //handle request for homepage
res.send(‘Hello world’) //sends a response
});

const port = 3000; //sets the port to listen on

server.listen(port,()=>{ //starts the server
console.log(‘Server is up and running on port ‘ + port)
});

64
Q

What is the simplest way to handle a request to the express server?

A

//by setting up a route

server.get(‘’,(req,res)=>{
res.send(‘Hello world!’)
})

65
Q

Which variables can be used in node to access the absolute path of a file and a directory

A

__dirname

__filename

66
Q

Which core NODE module can be used to manipulate or create path strings

A

path

67
Q

Which comman allows us to move up one directory?

A

../

68
Q

Which command allows us to move up two directories?

A

../../

69
Q

Which command allows us to access files in the same directory?

A

./

70
Q

What is the purpose of the public folder in node.js?

A

To serve up static pages such as html, css and javascript

71
Q

How to setup public folder in express server

A

const publicDirectoryPath = path.join(__dirname, ‘../public’)

server.use(express.static(publicDirectoryPath))

72
Q

Where are css files stored on a server?

A

inside the css folder within the public directory

73
Q

Where are html files stored on a server?

A

within the public directory

74
Q

Where are js scripts stored on a server?

A

inside the js folder within the public directory

75
Q

How to link stylesheet to html file

A
76
Q

How to link javascript to html file

A
77
Q

Where are images stored on a server?

A

in the img folder within the public folder

78
Q

Which npm module allows for templating?

A

hbs and handlebars

79
Q

What are template engines?

A

A template engine enables you to generate dynamic content in express. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.

80
Q

How do we setup a template engine to serve dynamic content in express?

A
//install handlebars module
npm i hbs
//set up view engine
server.set('view engine','hbs')

//create directory for views in the root directory

81
Q

How to render dynamic content to a browser using express.

A
//using a route 
//use res.render() instead of res.send()
// render takes two arguments 
// the file to be rendered's name
// an object with the dynamic content.

server.get(‘’,(req,res)=>{
res.render(‘filename’, {property:value})
});

82
Q

Setting a path for the views directory when working with dynamic content in express?

A
const viewsDirectoryPath = path.join(\_\_dirname,"../templates");
app.set('views',viewsDirectoryPath);
83
Q

How to structure templates directory?

A

root => templates => views, partials

server.set(‘views’, path)

84
Q

When working with the hbs how can we register the partials directory?

A

hbs.registerPartials(partialsDirectoryPath);

85
Q

What file extension does handlebar files use?

A

hbs

86
Q

How to add a partial to a handlebars file?

A

{{>filename}}

87
Q

Which character is used when setting up 404 pages in node express?

A

The wild card *

88
Q

Why does the route handler for 404 need to be last?

A

Node looks through each route handler in the order they are written. Node will ignore all route handlers after the wild card.

89
Q

What are the steps in setting up a basic servier using express?

A
  1. import modules
  2. create server
  3. set public directory
  4. create template machine
  5. set views directory
  6. register and set partials directory
  7. Set up route handlers
  8. Set up 404 route handler
  9. Start server
90
Q

How to access queries in the route handlers in express?

A

req.query

91
Q

How to handle query errors in express?

A

if(!req.query.searchterm){
return res.send({
error:”You must provide a search term”
})

92
Q

How to make client side http requests or api calls?

A
fetch(url).then((response)=>{
      response.json().then((data)=>{
           if(data.error){
              console.log(data.error)
           }else{
              console.log(data)
          }
       })
})
93
Q

How to get the information from an html form in javascript?

A
//save the form element
const weatherForm = document.querySelector('form');
//Save the input element
const search = document.querySelector("input")
//Add an event listener
weatherForm.addEventListener('submit',(e)=>{
    e.preventDefault() //prevent default
    const location = search.value() //get the value
    console.log('Testing form')
});
94
Q

How to prevent a form from refreshing the webpage after submission?

A

//use e.preventDefualt() to prevent default behaviour
weatherForm.addEventListener(‘submit’,(e)=>{
e.preventDefault()
console.log(‘Testing form’)

95
Q

Why is it better to make http requests from the server and not from the client side?

A

Because most browsers or websites will block cross-origen requests due to the specter vulnerabillty that would allow one access to a websites files and and content.

96
Q

Which folder don’t you want git to track?

A

node_modules

97
Q

How to recreate the node_modules folder?

A

npm install

98
Q

How to get git to not track the node_module folder?

A

Add a .gitignore file to the root directory and write node_modules/ in the file

99
Q

How to run a script from the package.json file?

A

npm run scriptname

100
Q

Why should global modules be avoided?

A

Because, when other developers download the project onto their machine, the global modules are not included, which means that the program wont run as expected or at all.

101
Q

How to uninstall a global module?

A

npm uninstall -g moduleName

102
Q

What does –save-dev do?

A

npm i module –save-dev installs a package as a dev dependency

103
Q

how are dev dependencies different from regular dependencies?

A

dev dependencies are not intalled in a production environment, only in a development environment

104
Q

When nodemon is installed locally, can we still access it using the nodemon command in the terminal?

A

No. The command only works when it is installed globally. In order to run it locally, you have to create a dev script

105
Q

REST API: What does REST stand for?

A

Representational State Transfer

106
Q

REST API: CRUD methods

A

Create: POST
Read: GET
Update: PATCH
Delete: DELETE

107
Q

REST API: Structure of http request

A
  1. Request line: Method, Path, protocol
  2. Multiple Request headers: Key/Value pairs
    a. ) Accept: application/json -tells the api what kind of data to return
    b. ) Connection: Keep-Alive -tells the api to keep the connection open as more requests are likely to be made.
    c. )Authorization: Bearer ey34Jdetc. -contain authorization keys
  3. Request body that contains Data provded as JSON
108
Q

REST API: Structure of http response

A
  1. Status line: Protocol, status code, text representation of status code
  2. Response Headers: Date, server, content type
  3. Body: contains JSON data
109
Q

A list of commonly installed npm packages

A
nodemon
express
request
mongodb
mongoose
validator
hbs
bcryptjs
jsonwebtoken
multer
sharp
@sendgrid/mail
env-cmd
jest
supertest
110
Q

REST API: How to configure the server to make incoming JSON data available as an object we can use

A

server.use(express.json());

this will make json available as an object accessibel on req.body

111
Q

Status codes

A

100: informational
200: success
300: redirection
400: Client Error codes
500: Server error codes

112
Q

Status codes

A

httpstatuses.com

100: informational
200: success
300: redirection
400: Client Error codes
500: Server error codes

113
Q

REST API: How to connect or access mongodb database from the server?

A
  1. import the mongoose client

require(‘./db/mongoose.js’)

2. import the models
const User = require('./db/models/user.js')
  1. instantiate an instance of the model in to be used by the routes
114
Q

REST API: Handling POST requests

A

//Post request creating a new user

server.post(“/users”,(req,res)=>{

const user = new User(req.body);

user.save().then(()=>{
    res.send(user);
}).catch((error)=>{
    res.status(400).send(error)
}) });
115
Q

REST API: What is the default status code returned from express?

A

200

116
Q

REST API: Handling GET or read requests

A

//in this example the Task model is not instantiate, instead .find() is called directly on the model itself

server.get("/tasks",(req,res)=>{
    Task.find({}).then((tasks)=>{
        res.send(tasks)
    }).catch((error)=>{
        res.status(500).send(error)
    })
});

//in retrieving a specific document, an id is added to the end of the url using :id, which is then accessed using req.params.id.

server.get("/tasks/:id",(req,res)=>{
    const id = req.params.id;
    Task.findById(id).then((task)=>{
        if(!task){
            return res.status(404).send()
        }
        res.send(task);
    }).catch((error)=>{
        res.status(500).send(error)
    })
});
117
Q

Difference between .every() and .foreach()

A

An important difference with .every() is that the test function may not always be called for every element in the array. Once the testing function returns false for any element, no more array elements are iterated. Therefore, the testing function should usually have no side effects.

.forEach() returns nothing - It iterates the Array performing a given action for each item in the Array.

118
Q

Which algorithm is used for encrypting user passwords?

A

Bcrypt

119
Q

How to hash a password with bcrypt?

A
const password = 'Red12345!'
const hashedPassword = await bcrypt.hash(password,8);
120
Q

Can a hashed password be decrypted?

A

No, it is one way

121
Q

If a hased password can’t be dycrypted, how can we compare a users password with the hashed one stored in the system?

A

const isMatch = await bcrypt.compare(userPassword, storedHashPassword)

122
Q

What is mongoose middleware?

A

Allows for the customization of mongoose models

123
Q

Which two mongoose methods can overide middleware?

A

.findById

.update

124
Q

Which npm package can be used to generate tokens?

A

jasonwebtoken

125
Q

What are the different parts of a JWT?

A

it has 3 parts: Header, Body,

The Header is a base 64 encoded json string that contains meta information about the type of token and the algorithem used ot generate it.

126
Q

What are the different parts of a JWT?

A

it has 3 parts: Header, Body, signiture

The Header is a base 64 encoded json string that contains meta information about the type of token and the algorithem used ot generate it.

The Body is a base 64 encoded string that contains the payload and a timestamp

The signitureis a base 64 encoded string that contains the signiture used to verify the token

127
Q

How to create a web token?

A

const token = jwt.sign({_id:’abc123’}, ‘secretKey’);

128
Q

How to verify a toke?

A

const data = jwt.verify(token,’secretKey’);

returns a payload object if verified, otherwise it throws an error

129
Q

Mongoose: How to define methods to be called on the model?

A

userSchema.statics.methodName(){

}

130
Q

Mongoose: How to define methods to be called on a model instance?

A

userSchema.methods.methodName(){}

131
Q

What is express middleware?

A

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

132
Q

How to setup express middleware?

A

//middleware needs to be created above the route handlers for it to work

server.use((req,res,next)=>{
    if(req.method === 'GET'){
        res.send('GET requests are disabled')
    } else {
        next()
    }
});
133
Q

How is authentication tokens sent to the route handlers or server

A

placed in the header

Key: Authorization
Value: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTk5NjI0M2FiZTA3ZTBkNDAzYjE5YzUiLCJpYXQiOjE1ODcxNzk5OTN9.eGfK8IoVIbbpyH2SxTR9_Liw7YTGDisVbc5MDMdaqFE

134
Q

How to populate a model with fields from a related model?

A
//test
const Task = require('./db/models/task');
const User = require('./db/models/user');

const main = async ()=>{
const user = await User.findById(‘5e99a4a5e97c45531011fe95’);
await user.populate(‘tasks’).execPopulate();
console.log(user.tasks)
}

main();

135
Q

How to add a time stamp to a data model?

A

when defining the modelSchema pass the following object in as the second argument

{timestamps:true}

136
Q

Which npm library allows you to upload media files to the data base?

A

multer

137
Q

Multer: How to limit file size and filter for specific file types?

A
const upload = multer({
    dest:"avatar",
    limits:{
        fileSize:1000000
    },
    fileFilter(req,file,cb){
        if(!file.originalname.endsWith('.pdf')){
            cb(new Error('Please upload a pdf!'))
        }
    cb(undefined,true)
} });

router.post(‘/users/uploads/avatar’,upload.single(‘avatar’), (req,res)=>{
res.send()
});

138
Q

Multer: How to use regex to filter for specific file types

A
const upload = multer({
    dest:"avatar",
    limits:{
        fileSize:1000000
    },
    fileFilter(req,file,cb){
        if(!file.originalname.match(/\.(jpg|jpeg|png)$/)){
            return cb(new Error('Please upload a word document!'))
        }
    cb(undefined,true)
} });
139
Q

Multer: How to handle errors, when client uploads the wrong file type?

A

router.post(‘/users/uploads/avatar’,upload.single(‘avatar’), (req,res)=>{
res.send()
},(error,req,res,next)=>{
res.status(400).send({error:error.message})
});

140
Q

How to set an image in html with binary code instead of a file?

A

<img></img>

141
Q

When returning a file to a client, what needs to be set before it is sent?

A

Need to set the header

res.set(‘content-type’,’image/jpg’)

or

res.set(‘content-type’,’application/json’)

142
Q

Which module helps to reformat an image?

A

sharp

143
Q

How to reformat an image using sharp?

A
const buffer = await sharp(req.file.buffer).resize({width:250, height:250}).png().toBuffer();
        req.user.avatar = buffer;
144
Q

How to setup environment variables?

A
  1. install npm i env-cmd
  2. Create a dev.env file
  3. Setup variables in the file
  4. access variables in relevant locations using process.env.ENV_NAME
  5. Set the dev script to “env-cmd -f ./dev.env nodemone src/index.js”