ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Mongoose
    스터디노트/DB 2022. 3. 28. 11:13

    Mongoose

    • MongoDB ODM(Object Document Mapper)

    예시

    • 연결 (database.js)
        import Mongoose from "mongoose";
    
        export async function connectDB() {
            return Mongoose.connect(url, options);
        }
    
        export function useVirtualId(schema) {
          schema.virtual('id').get(function() {
              return this._id.toString(); // this._id는 object이므로 toString해준다.
          });
    
          schema.set("toJSON", {virtuals : true}); // id정보 json에 포함
          schema.set("toObject", {virtuals : true}); // console.log에 가상의 필드 추가
        }
    • userSchema
        import Mongoose from "mongoose";
        import {useVirtualId} from "database.js 경로";
    
        const userSchema = new Mongoose.Schema({
            username : {type : String, required : true},
              name : {type : String, required : true},
              email : {type : String, required : true},
              password : {type : String, required : true},
              url : String
        });
    
        useVirtualId(userSchema);
        const User = Mongoose.model("User", userSchema); // User의 collection을 userschema와 연결
    
        export async function createUser(user) {
            return new User(user).save().then(data => data.id); // data안에 있는 id를 전달
        }
    
        export async function findByUsername(username) {
            return User.findOne({username});
        }
    
        export async function findById(id) {
            return User.findById({id});
        }
    
        export async function updateUser(id, email) {
            return User.findByIdAndUpdate(id, {email}, {returnOriginal : false}); // update된 정보를 return
        }
    
        export async function removeUser(id) {
            return User.findByIdAndDelete(id);
        }

    참고자료

    '스터디노트 > DB' 카테고리의 다른 글

    MongoDB Sharding이란??  (0) 2022.04.14
    mongodump, mongorestore  (0) 2022.04.06
    MongoDB  (0) 2022.03.22
    ALGORITHM=INPLACE, LOCK=NONE으로 테이블 변경하기  (0) 2022.02.16
    MySQL IFNULL, CASE WHEN, COALESCE  (0) 2021.12.15
Designed by Tistory.