2016-12-19 10 views
1

学習目的のためにFullNameからfirstNameとlastNameを別々にしようとしています。私は、このアプリケーションを実行するために行くとき、私は2つのエラーa)はマングーススキーマ学生が「firstNameの」仮想Bを持っているの取得)マングースのスキーマ学生は、以下の「lastNameの」仮想フルネームのfirstNameとlastNameをNode.jsのMongoDBに残す

は私が

var mongoose = require('mongoose'); 

var schema = new mongoose.Schema({ 
    name: { type: String, required: true }, 
    courses: [{ type: String, ref: 'Course' }] 
}); 

/* Returns the student's first name, which we will define 
* to be everything up to the first space in the student's name. 
* For instance, "William Bruce Bailey" -> "William" */ 
schema.virtual('firstName').set(function(name) { 
    var split = name.split(' '); 
    this.firstName = split[0]; 
}); 

/* Returns the student's last name, which we will define 
* to be everything after the last space in the student's name. 
* For instance, "William Bruce Bailey" -> "Bailey" */ 
schema.virtual('lastName').set(function(name) { 
    var split = name.split(' '); 
    this.lastName = split[split.length - 1]; 
}); 

module.exports = schema; 

答えて

0
をデバッグしていたコードであり Mongooseドキュメントから

virtualsを

Virtualsは、Yドキュメントプロパティでありますとsetではなく で、MongoDBに保持されることはありません。 gettersは、 フィールドの書式設定または結合には便利ですが、settersは、単一の値を複数の値に分割して保存する場合に便利です。

あなたはnameプロパティは、DBに固執してきたように、あなたがfirstNamelastNameからnameプロパティを定義するためにsettersを使用することができるのに対し、あなたはfirstNamelastNameとしてそれを分割するgettersを使用する必要があります。

だから、virtualsのためのあなたのコードは、指し示す

/* Returns the student's first name, which we will define 
* to be everything up to the first space in the student's name. 
* For instance, "William Bruce Bailey" -> "William" */ 
schema.virtual('firstName').get(function() { 
    var split = this.name.split(' '); 
    return split[0]; 
}); 

/* Returns the student's last name, which we will define 
* to be everything after the last space in the student's name. 
* For instance, "William Bruce Bailey" -> "Bailey" */ 
schema.virtual('lastName').get(function() { 
    var split = this.name.split(' '); 
    return split[split.length - 1]; 
}); 
+0

感謝する必要があります – DotNET

関連する問題