Mongoose: μ€‘μ²©λœ 가상, ν•˜μœ„ λ¬Έμ„œμ˜ 가상 지원

에 λ§Œλ“  2011λ…„ 02μ›” 12일  Β·  6μ½”λ©˜νŠΈ  Β·  좜처: Automattic/mongoose

var Page = new Schema({
    author: {
        first_name: String
      , last_name: String
    }
});
Page.virtual("author.full_name").get(function() {
    return this.author.first_name + " " + this.author.last_name;
});

// Later
myPage = new Page({author: {first_name: "John", last_name: "Doe"}});
myPage.author.full_name; // == undefined
myPage.get("author.full_name"); // == "John Doe"

자체 κ°€μƒμœΌλ‘œ μž‘μ„±μžλ₯Ό μœ„ν•œ μƒˆ μŠ€ν‚€λ§ˆλ₯Ό λ§Œλ“€λ €κ³  μ‹œλ„ν•˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. μž‘λ™ν•  μˆ˜λ„ μžˆμ§€λ§Œ λ‹€λ₯Έ 문제 λ³΄κ³ μ„œμ— λ”°λ₯΄λ©΄ ν•˜μœ„ μŠ€ν‚€λ§ˆλŠ” 일반 ν•˜μœ„ λ¬Έμ„œκ°€ μ•„λ‹Œ λ°°μ—΄ atmμ—μ„œ 졜적으둜 μž‘λ™ν•©λ‹ˆλ‹€.

μ†ŒμŠ€λ₯Ό 보면 μŠ€ν‚€λ§ˆ νŠΈλ¦¬μ— 가상을 μΆ”κ°€ν•˜λŠ” λ™μ•ˆ μ˜λ¦¬ν•œ split(".") 논리가 λˆ„λ½λ˜μ–΄ λΆˆκ°€λŠ₯ν•΄ 보이지 μ•ŠμŠ΅λ‹ˆλ‹€.

get λ©”μ„œλ“œλŠ” λ‹ΉλΆ„κ°„ 잘 μž‘λ™ν•˜μ§€λ§Œ λ‹€λ₯Έ ꡬ문이 더 μ’‹μŠ΅λ‹ˆλ‹€. :)

κ°€μž₯ μœ μš©ν•œ λŒ“κΈ€

μœ„μ˜ μ†”λ£¨μ…˜μ€ μž‘λ™ν•˜μ§€λ§Œ 쀑첩 μŠ€ν‚€λ§ˆμ— λŒ€ν•΄ 가상을 μ„€μ •ν•΄μ•Ό ν•©λ‹ˆλ‹€.

Variation.set('toJSON', {
    virtuals: true
});

λͺ¨λ“  6 λŒ“κΈ€

λ¬Όλ‘  이 μˆ˜μ • 사항은 ν•˜μœ„ λ¬Έμ„œμ˜ λ©”μ„œλ“œμ—λ„ μ μš©λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.

μž‘μ„±μžκ°€ 배열이면 μ–΄λ–»κ²Œ λ©λ‹ˆκΉŒ? 이 μ–΄λ ˆμ΄ κ°κ°μ—μ„œ 가상 μž‘μ—…μ„ μˆ˜ν–‰ν•  수 μžˆμŠ΅λ‹ˆκΉŒ?

μ–΄λ ˆμ΄μ— λŒ€ν•œ +1 지원

μ–΄λ ˆμ΄μ— λŒ€ν•œ +100 지원

그것을 μ•Œμ•„ λƒˆμŠ΅λ‹ˆλ‹€ :.

var Variation = new Schema({
  label: {
    type: String
  }
});

// Virtual must be defined before the subschema is assigned to parent schema
Variation.virtual("name").get(function() {

  // Parent is accessible
  var parent = this.parent();
  return parent.title + ' ' + this.label;
});


var Product = new Schema({
  title: {
    type: String
  }

  variations: {
    type: [Variation]
  }
});

μœ„μ˜ μ†”λ£¨μ…˜μ€ μž‘λ™ν•˜μ§€λ§Œ 쀑첩 μŠ€ν‚€λ§ˆμ— λŒ€ν•΄ 가상을 μ„€μ •ν•΄μ•Ό ν•©λ‹ˆλ‹€.

Variation.set('toJSON', {
    virtuals: true
});
이 νŽ˜μ΄μ§€κ°€ 도움이 λ˜μ—ˆλ‚˜μš”?
0 / 5 - 0 λ“±κΈ‰