Skip to content

Mongoose

gyim1345 edited this page Dec 21, 2020 · 2 revisions

πŸ“Œ Mongoose μ†Œκ°œ

MongooseλŠ” 데이터λ₯Ό μœ„ν•œ λͺ¨λΈλ§ ν™˜κ²½μ„ μ œκ³΅ν•˜λŠ” ODM(object data modeling) λΌμ΄λΈŒλŸ¬λ¦¬λ‹€.

πŸ“Œ Object modeling

    // user schema μ •μ˜
    const userSchema = new mongoose.Schema({
      name: {
        first: String,
        last: { type: String, trim: true }
      },
      age: { type: Number, min: 0 }
    });
   
    // user schema μ‚¬μš©ν•˜μ—¬ λͺ¨λΈ 생성
    const PUser = mongoose.model('PowerUsers', userSchema);
    
    // λͺ¨λΈλ‘œ μœ μ € 생성
    const johndoe = new PUser ({
      name: { first: 'John', last: '  Doe   ' },
      age: 25
    });

    // μ €μž₯
    johndoe.save(function (err) {if (err) console.log ('Error on save!')});

πŸ“Œ ν”„λ‘œμ νŠΈμ—μ„œ λŠλ‚€μ 

λ°μ΄ν„°μ˜ type validationκ³Ό κ·Έμ™Έ μžμž˜ν•œκ²ƒμ„ μ‰½κ²Œ λ„μ™€μ€˜μ„œ λ„ˆλ¬΄ μ’‹μ•˜λ‹€. 섀정도 λ„ˆλ¬΄ μ‰½κ²Œ λ˜μ„œ μ’‹μ•˜λ‹€. κ°€λ Ή default값을 μΆ”κ°€ ν˜Ήμ€ μˆ˜μ • ν• λ•Œ.

Clone this wiki locally