[MongoDB] Mongoose - 가상 Mongoose

Zero·2023년 3월 14일
0

MongoDB

목록 보기
13/14

Virtuals

  • 실제 데이터베이스 자체에 존재하지 않는 스키마에 특성을 추가할 수 있게 해준다.
  • firstlast가 있는 user Model이 있다. fullName에 접근하고 싶을 때 데이터베이스에 저장할 필요는 없고, 데이터베이스에 있는 것처럼 접근할 수 있는 특성을 만들자


코드로 살펴보자 ~
const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost:27017/shopApp")
  .then(() => {
    console.log("Connection Success");
  })
  .catch((err) => {
    console.log("Oh no Error!");
    console.log(err);
  });

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

personSchema.virtual("fullName").get(function () {
  return `${this.first} ${this.last}`; // this는 사람 개인이자 작업하는 인스턴스를 참조하며 인스턴스 메서드를 추가하는 것과는 다르다
  // 스키마에 fullName 혹은 get fullName이라 불리는 인스턴스 메서드를 작성할 수 있지만 차이점은 실제 특성인 것처럼 작동한다
});

const Person = mongoose.model("Person", personSchema);

const tom = new Person({first:"tom", last:"jerry"})

tom
{
 	first: "tom",
  	last : "jerry",
    _id : ~~~~~~~~~~
}
    
tom.fullName
// 'tom jerry'
tom.save()
  
> db.people.find()
  {
        "_id" : ObjectId("63d68f13aa711a54346b7dea"),
        "first" : "tom",
        "last" : "jerry",
        "__v" : 0
}
  
  • fullName 은 실제로 존재하지 않는다.
  • 해당 특성은 데이터베이스 내부에 존재하는 것이 아닌 자바스크립트의 Mongoose에서만 가능하다.

set()을 이용하면 업데이트가 가능함.

0개의 댓글