2016-12-19 23 views
1

我試圖讓從全名獨立firstName和lastName學習的目的。當我去運行這個應用程序,我得到兩個錯誤)貓鼬架構學生有一個「的firstName」虛擬B)的貓鼬架構學生有一個「lastName的」虛擬從全名獲得firstName和lastName MongoDB中堅持的Node.js

下面是代碼我調試

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您可以同時getset但 沒有得到保存到MongoDB。的getters是 格式化或結合領域是有用的,而setters是 有用去構成一個單一的值轉換成存儲多個值。

你有name屬性在DB堅持,你應該使用getters將其分割爲firstNamelastName,而你可以使用settersfirstNamelastName定義name財產。指點

所以你對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

相關問題