TIL032_210501

JIYOONยท2021๋…„ 5์›” 2์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
32/42
post-thumbnail

๐ŸŠ ๊ฐ์ƒ

๐Ÿ“™ ์—ดํ’ˆํƒ€ ์ฝ”๋”ฉ ์‹œ๊ฐ„ 10hour
๐Ÿ‘๐Ÿผ -
๐Ÿ‘Ž๐Ÿผ -

๐Ÿš€ ๋ชฉํ‘œ

  • Udemy : The web developer bootcamp 2021 ๊ฐ•์ขŒ ์ˆ˜๊ฐ• (458/682)
  • ๊ฐœ์ธ ํ”„๋กœ์ ํŠธ ์ง„ํ–‰
  • Udemy : Javascript algorithms and data structures ๊ฐ•์ขŒ ์ˆ˜๊ฐ• (0/249)

๐Ÿ“ฃ The Web Developer Bootcamp 2021

37. Connecting to mongo with mongoose

383. Updating with mongoose

Movie.updateOne({title:'Amadeus'},{year:1984}).then(res=>console.log(res))
Movie.updateMany({title:{$in:['Amadeus','Stand by me']}}, {score:10}).then(res=>console.log(res))

Movie.findOneAndUpdate({title: 'The Iron Giant'}, {score: 7.0}).then(m=>console.log(m))
//์—ฌ๋Ÿฌ ๊ฐœ ์ฐพ๋”๋ผ๋„ ์ฒซ๋ฒˆ์งธ๋งŒ ์—…๋ฐ์ดํŠธํ•จ
//์—…๋ฐ์ดํŠธ๋๋”๋ผ๋„ ์ด์ „ ๊ฐ’ ํ‘œ์‹œํ•ด์ฃผ๋ฏ€๋กœ ํ—ท๊ฐˆ๋ฆฌ์ง€ ๋ง ๊ฒƒ

Movie.findOneAndUpdate({title: 'The Iron Giant'}, {score: 7.8},{new:true}).then(m=>console.log(m))
//์ด๋ ‡๊ฒŒ ์„ธ๋ฒˆ์งธ์— ์˜ต์…˜ ์„ค์ •ํ•ด์ฃผ๋ฉด modified๋œ ๊ฐ’ ๋ณด์—ฌ์คŒ

384. Deleting with mongoose

Movie.remove({title: 'Amelie'}).then(msg=>console.log(msg))
-> remove ๋ณด๋‹ค๋Š” deleteOne, deleteMany, bulkWrite๋ฅผ ์“ธ ๊ฒƒ

Movie.deleteMany({year:{$gte:1999}}).then(msg => console.log(msg))
Movie.findOneAndDelete({title: 'The Iron Giant'}, {score: 7.8}).then(m=>console.log(m))

385. Mongoose schema validations

386. Additional schema constraints

๊ณต์‹๋ฌธ์„œ: mongoose shema type

//connection to mongodb logic
const mongoose = require('mongoose');
mongoose
  .connect('mongodb://localhost:27017/shopApp', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('connected');
  })
  .catch((err) => {
    console.log(err);
    console.log('error');
  });
//define shema
const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    maxlength: 20,
  },
  price: {
    type: Number,
    required: true,
    min: 0,
  },
  onSale: {
    type: Boolean,
    default: false,
  },
  categories: {
    type: [String],
    default: ['Cycling'],
  },
  //object
  qty: {
    online: {
      type: Number,
      default: 0,
    },
    inStore: {
      type: Number,
      default: 0,
    },
  },
});
//take schema nad turn it into a model
const Product = mongoose.model('Product', productSchema);

const bike = new Product({
  name: 'Mountain Bike',
  price: 599,
  categories: ['Cycling', 'Safety'],
});
bike
  .save()
  .then((data) => {
    console.log('It worked');
    console.log(data);
  })
  .catch((err) => {
    console.log(err.errors.name.properties.message);
  });

//module์—์„œ node product.js ํ•˜๋ฉด ์—ฐ๊ฒฐ๋จ
//mongo shell -> show dbs๋กœ ํ™•์ธ ํ›„ use shopApp
//mongo shell -> db.products.find()

387. Validating mongoose updates

schema์˜ ๋‹จ์  : ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ ๋งŒ๋“ค ๋•Œ๋Š” ์ ์šฉ๋˜์ง€๋งŒ ์—…๋ฐ์ดํŠธํ•  ๋•Œ๋Š” ์ ์šฉ๋˜์ง€ ์•Š์Œ

Product.findOneAndUpdate({name: 'Mountain Bike'}, {price: -10.99}, {new: true, runValidators: true})

new: true -> ์—…๋ฐ์ดํŠธ๋œ ๋ฐ์ดํ„ฐ ๋ณด์—ฌ์คŒ
runValidators: true -> ์„ค์ •ํ•œ schema๊ฐ€ ์—…๋ฐ์ดํŠธ๋  ๋•Œ๋„ ์ ์šฉ๋œ๋‹ค

388. Mongoose validation errors

how to set up a custom validator error messages

  price: {
    type: Number,
    required: true,
    min: [0, 'Price must be positive ya dodo'],
  }

enum

checks if the value is in the given array

  size: {
    type: String,
    enum: ['S', 'M', 'L']
  }

389. Model instance methods

๊ณต์‹๋ฌธ์„œ: built-in instance methods

defining or addign functionality onto the model

used for check credetials or authenticate or validate where it will check a password input against what we have stored in the database.

productSchema.methods.greet = function () {
  console.log('hello howdy');
  console.log(`-from ${this.name}`);
};

productSchema.methods.toggleOnSale = function () {
  this.onSale = !this.onSale;
  return this.save();
  //anytime we call save, it does take time -> asynchronous operation
};

productSchema.methods.addCategory = function (newCat) {
  this.categories.push(newCat);
  return this.save();
};

const findProduct = async () => {
  const foundProduct = await Product.findOne({ name: 'Bike Helmet' });
  foundProduct.greet();
  console.log(foundProduct);
  await foundProduct.toggleOnSale();
  console.log(foundProduct);
  await foundProduct.addCategory('Outdoors');
  console.log(foundProduct);
};

findProduct();

390. Adding model static methods

์ •์ (static) ๋ฉ”์†Œ๋“œ์™€ ์ธ์Šคํ„ด์Šค(instance) ๋ฉ”์†Œ๋“œ

static method : methods that live on the model itself, not on instances of the model.
These methods won't act upon individual instances.
static method์—์„œ๋Š” this keyword๊ฐ€ model class itself๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.

instance method : instance method ๋‚ด์—์„œ this keyword๋Š” individual instance๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค
์ฐธ์กฐ๋ณ€์ˆ˜

๊ฐ์ฒด์™€ ์ธ์Šคํ„ด์Šค

์—„๊ฒฉํ•˜๊ฒŒ ๊ฐ์ฒด์™€ ์ธ์Šคํ„ด์Šค๋ฅผ ๋‚˜๋ˆ„๊ธด ์–ด๋ ต๋‹ค, ๊ฐ™๊ฒŒ ์“ฐ์ด๊ธฐ๋„.
์ฐธ๊ณ ๋งํฌ: heejeong Kwon

Adding model static methods

productSchema.statics.fireSale = function () {
  return this.updateMany({}, { onSale: true, price: 0 });
};
Product.fireSale().then((res) => console.log(res));

391. Mongoose virtuals

virtuals

Give us ability to add properties to a schema that don't actually exist in the database itself, but that we have access to, thanks to mongoose.
These are usually synthesis of multiple properties in a database or something that could be derived from the database.
-> creates virtual type with a given name
-> mongodb์— ์ €์žฅ๋˜์ง€ ์•Š๋Š” attribute
-> set,get function์„ ์ •์˜

instance method ๋Œ€์‹  ์“ฐ๋Š” ์ด์œ 

virtual์€ actual property์ฒ˜๋Ÿผ ํ–‰๋™ํ•œ๋‹ค.
๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅ๋  ํ•„์š” ์—†์ง€๋งŒ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์žˆ๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” property๊ฐ€ ์žˆ์œผ๋ฉด ์ข‹์„ ๋•Œ

how to use virtual

const personSchema = new mongoose.Schema({
  first: String,
  last: String,
});

personSchema.virtual('fullName').get(function () {
  return `${this.first}${this.last}`;
});

const Person = mongoose.model('Person', personSchema);
const tammy = new Person({first: 'Tammy', last: 'Chow'})
tammy.fullName //Tammy Chow
tammy.save() //people collectioin์ด ์ƒ๊น€(์ž๋™์œผ๋กœ ๋ณต์ˆ˜ํ™”ํ•ด์คŒ)
db.people.find() //fullName์€ ์ €์žฅ๋ผ์žˆ์ง€ ์•Š์Œ

392. Defining mongoose middleware

personSchema.pre('save', async function () {
  console.log('about to save');
});
personSchema.post('save', async function () {
  console.log('just saved');
});

์ฐธ๊ณ ๋งํฌ: Zero Cho

userSchema.pre('save', function(next) {
  if (!this.email) { // email ํ•„๋“œ๊ฐ€ ์—†์œผ๋ฉด ์—๋Ÿฌ ํ‘œ์‹œ ํ›„ ์ €์žฅ ์ทจ์†Œ
    throw '์ด๋ฉ”์ผ์ด ์—†์Šต๋‹ˆ๋‹ค';
  }
  if (!this.createdAt) { // createdAt ํ•„๋“œ๊ฐ€ ์—†์œผ๋ฉด ์ถ”๊ฐ€
    this.createdAt = new Date();
  }
  next();
});
userSchema.post('find', function(result) {
  console.log('์ €์žฅ ์™„๋ฃŒ', result);

Two options

  1. Accept a 'next' parameter in our callback and then execute next at the very end of function
  2. Return a promise from a function

๐Ÿ“ฃ Javascript algorithms and data structures masterclass

chrome - source - snippet - run: cmd+return
/ terminal, nodejs, codepen, jsbin ๋“ฑ๋“ฑ์—์„œ ์‹คํ–‰ํ•ด๋„ ๋จ

Big O notation

Intro to Big O

๋น…์˜ค ํ‘œ๊ธฐ๋ฒ•

Timing our code

An example : sum of all numbers from 1 up to (and including) some number n.

console.log("hello from ")

function addUpTo1(n) {
    let total = 0;
    for (let i = 1; i<=n; i++) {
        total+=i;
    }
    return total;
}
console.log(addUpTo1(7))

function addUpTo2(n) {
    return n*(n+1)/2;
}
console.log(addUpTo2(7))

What does better mean?

  1. faster? -> different machines will record different times, same machine will record different times too.
  2. less memory-intensive?
  3. more readable?

Counting Operations

addUpTo2 has 3 simple operations(1 multiplication, 1 addition, 1 division), regardless of the size of n.

addUpTo1 -> because of loop, number of operations grows roughly proportionally with n.

Official intro to Big O

Big O definition

f(n) could be linear - input and runtime -> as n(input) scales, runtime scales as well.
f(n) could be quadratic - n grows, runtime related to square of n
f(n) could be constant
f(n) could be something entirely different

Example

addUpTo2 : always 3 operations -> O(1)

addUpTo1 : number of operations bounded by a multiple of n -> O(n)

More example

nested loop -> O(n^2)

Simplifying Big O Expressions

Regardless of the exact number, the number of operations grows roughly proportionally with n -> constants and smaller terms don't matter

Big O shorthands

  1. arithmetic(์‚ฐ์ˆ˜) operation -> constant
  2. variable assignment -> constant
  3. accessing elements in an array(by index) or object(by key) -> constant
  4. length of the loop times the complexity of whatever happens inside of the loop

Space Complexity

auxiliary space complexity ๋ณด์กฐ ๊ณต๊ฐ„ ๋ณต์žก๋„
-> refer to space required by the algorithm, not including space taken up by the inputs
space complexity ๊ณต๊ฐ„ ๋ณต์žก๋„ -> ๊ฐ•์˜ ๋‚ด์—์„œ ๊ณต๊ฐ„๋ณต์žก๋„ ๋งํ•˜๋ฉด ๋ณด์กฐ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ ์˜๋ฏธํ•˜๋Š” ๊ฒƒ

Example

function sum(arr) {
  let total = 0;
  for (let i = 0; i < arr.length; i++) {
    total += arr\[i];
  }
  return total;
}

total -> number, i -> number
adding two variable, not making new variable -> constant space

Another example

function double(arr) {
  let newArr = [];
  for (let i = 0; i<arr.length; i++) {
    newArr.push(2*arr[i]);
  }
  return newArr;
}

-> O(n) space

Logs and Section Recap

Log

Logarithm complexity

O(n^2) > O(nlog n) > O(n) > O(log n) > O(1)

0๊ฐœ์˜ ๋Œ“๊ธ€