๐ ์ดํํ ์ฝ๋ฉ ์๊ฐ 10hour
๐๐ผ -
๐๐ผ -
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๋ ๊ฐ ๋ณด์ฌ์ค
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))
๊ณต์๋ฌธ์: 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()
schema์ ๋จ์ : ์๋ก์ด ๋ฐ์ดํฐ ๋ง๋ค ๋๋ ์ ์ฉ๋์ง๋ง ์ ๋ฐ์ดํธํ ๋๋ ์ ์ฉ๋์ง ์์
Product.findOneAndUpdate({name: 'Mountain Bike'}, {price: -10.99}, {new: true, runValidators: true})
new: true -> ์
๋ฐ์ดํธ๋ ๋ฐ์ดํฐ ๋ณด์ฌ์ค
runValidators: true -> ์ค์ ํ schema๊ฐ ์
๋ฐ์ดํธ๋ ๋๋ ์ ์ฉ๋๋ค
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']
}
๊ณต์๋ฌธ์: 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();
์ ์ (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));
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์ ์ ์ฅ๋ผ์์ง ์์
personSchema.pre('save', async function () {
console.log('about to save');
});
personSchema.post('save', async function () {
console.log('just saved');
});
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
chrome - source - snippet - run: cmd+return
/ terminal, nodejs, codepen, jsbin ๋ฑ๋ฑ์์ ์คํํด๋ ๋จ
๋น ์ค ํ๊ธฐ๋ฒ
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?
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.
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)
Regardless of the exact number, the number of operations grows roughly proportionally with n -> constants and smaller terms don't matter
Big O shorthands
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
Log
Logarithm complexity
O(n^2) > O(nlog n) > O(n) > O(log n) > O(1)