TIL036_210511

JIYOONΒ·2021λ…„ 5μ›” 11일
0

TIL

λͺ©λ‘ 보기
36/42
post-thumbnail

🍊 감상

πŸ“™ μ—΄ν’ˆνƒ€ μ½”λ”© μ‹œκ°„ 5hour
πŸ‘πŸΌ -
πŸ‘ŽπŸΌ -

πŸš€ λͺ©ν‘œ

Udemy : The web developer bootcamp 2021 κ°•μ’Œ μˆ˜κ°• (501/682)
개인 ν”„λ‘œμ νŠΈ 진행
Udemy : Javascript algorithms and data structures κ°•μ’Œ μˆ˜κ°• (11/249)

πŸ“£ The Web Developer Bootcamp 2021

42. Handling Errors In Express Apps

436. Defining An Async Utility

function wrapAsync(fn) {
  return function (req, res, next) {
    fn(req, res, next).catch((e) => next(e));
  };
}

app.get(
  '/products/:id',
  wrapAsync(async (req, res, next) => {
    const { id } = req.params;
    const product = await Product.findById(id);
    if (!product) {
      throw new AppError('Product not found', 404);
    }
    res.render('products/show', { product });
  })
);

437. Differentiating Mongoose Errors

const handleValidationErr = (err) => {
  console.dir(err);
  return new AppError(`Validation Failed...${err.message}, 400`);
};

app.use((err, req, res, next) => {
  console.log(err.name);
  if (err.name === 'ValidationError') err = handleValidationErr(err);
  next(err);
});

44. Data Relationships With Mongo

448. SQL Relationships Overview

449. One to Few

const mongoose = require('mongoose');
mongoose
  .connect('mongodb://localhost:27017/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('Mongo connection open');
  })
  .catch((err) => {
    console.log('Mongo connection error');
    console.log(err);
  });

const userSchema = new mongoose.Schema({
  first: String,
  last: String,
  addresses: [
    {
      _id: { id: false },
      street: String,
      city: String,
      state: String,
      country: String,
    },
  ],
});

const User = mongoose.model('User', userSchema);

const makeUser = async () => {
  const u = new User({
    first: 'Harry',
    last: 'Potter',
  });
  u.addresses.push({
    street: '123 Sesame St.',
    city: 'New York',
    state: 'NY',
    coutry: 'USA',
  });
  const res = await u.save();
  console.log(res);
};

const addAdress = async (id) => {
  const user = await User.findById(id);
  user.addresses.push({
    street: '99 3rd St.',
    city: 'New York',
    state: 'NY',
    country: 'USA',
  });
  const res = await user.save();
  console.log(res);
};

makeUser();

450-451. One to Many & Mongoose Populate

populate : ObjectIdλ₯Ό μ‹€μ œ 객체둜 μΉ˜ν™˜ν•œλ‹€

Store references on the parent.

참고링크: Zero Cho

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

mongoose
  .connect('mongodb://localhost:27017/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('Mongo connection open');
  })
  .catch((err) => {
    console.log('Mongo connection error');
    console.log(err);
  });

const productSchema = new Schema({
  name: String,
  price: Number,
  season: {
    type: String,
    enum: ['Spring', 'Summer', 'Fall', 'Winter'],
  },
});

const farmSchema = new Schema({
  name: String,
  city: String,
  products: [{ type: Schema.Types.ObjectId, ref: 'Product' }],
});

const Product = mongoose.model('Product', productSchema);
const Farm = mongoose.model('Farm', farmSchema);

Product.insertMany([
  { name: 'Goddess Melon', price: 4.99, season: 'Summer' },
  { name: 'Sugar Baby Watermelon', price: 4.99, season: 'Summer' },
  { name: 'Asparagus', price: 3.99, season: 'Spring' },
]);

const makeFarm = async () => {
  const farm = new Farm({ name: 'Full Belly Farms', city: 'Guinda, CA' });
  const melon = await Product.findOne({ name: 'Goddess Melon' });
  farm.products.push(melon);
  await farm.save();
  console.log(farm);
};

const addProduct = async () => {
  const farm = await Farm.findOne({ name: 'Full Belly Farms' });
  const watermelon = await Product.findOne({ name: 'Sugar Baby Watermelon' });
  farm.products.push(watermelon);
  await farm.save();
  console.log(farm);
};

makeFarm();
addProduct();

Farm.findOne({ name: 'Full Belly Farms' })
  .populate('products')
  .then((farm) => console.log(farm));

452. One to "Bajillions"

Store reference on the child.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

mongoose
  .connect('mongodb://localhost:27017/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('Mongo connection open');
  })
  .catch((err) => {
    console.log('Mongo connection error');
    console.log(err);
  });

const userSchema = new Schema({
  username: String,
  age: Number,
});

const tweetSchema = new Schema({
  text: String,
  likes: Number,
  user: { type: Schema.Types.ObjectId, ref: 'User' },
});

const User = mongoose.model('User', userSchema);
const Tweet = mongoose.model('Tweet', tweetSchema);

const makeTweets = async () => {
  const user = new User({ username: 'chickenfan99', age: 61 });
  const tweet1 = new Tweet({
    text: 'omg I love my chicken family',
    likes: 0,
  });
  tweet1.user = user;
  user.save();
  tweet1.save();
};

const makeTweets2 = async () => {
  const user = await User.findOne({ username: 'chickenfan99' });
  const tweet2 = new Tweet({
    text: 'bock bock bock my chickens make noises',
    likes: 99,
  });
  tweet2.user = user;
  tweet1.save();
};

makeTweets();
makeTweets2();

const findTweet = async () => {
  const t = await Tweet.find({}).populate('user', 'name');
  console.log(t);
};

findTweet();

참고링크: matisse

453. Mongo Schema Design

κ³΅μ‹λ¬Έμ„œ: mongoDB Blog

45. Mongo Relationships With Express

0개의 λŒ“κΈ€