2015-09-13 39 views
0

我想用Mongoose ORM檢查一些MongoDB字段的最佳方法。已經用Mongoose檢查MongoDB字段

const userSchema = new Schema({ 
    last_name: { 
    type: String, 
    select: false, 
    } 
}); 

userSchema.virtual('last_name_initial').get(function() { 
    return this.last_name.substr(0,1).toUpperCase(); 
}); 

不會去做這件事,因爲last_name設置爲select: false,很顯然,我不想當你指定{select: false}發送回last_name

+0

https://github.com/Automattic/mongoose/issues/1195 – ZeMoon

回答

2

在任何領域中的模式,現場被排除在查詢默認情況下。所以,在這種情況下,你的虛擬現場只會工作已經質疑這樣的目標:

User.find().select('+last_name').exec(function (err, users) { 

    //The virtual field should be available here. 
    console.log(users[0].last_name_initial); 
}); 

如果你想在虛擬領域始終可用,而不必明確包括選擇字段,則這將是最好使用另一種方法,而不是{select: false}。您可以排除默認領域

一種方式是通過重寫toJSON方法(source有同樣的問題,因爲你)

userSchema.methods.toJSON = function() { 
    var obj = this.toObject() 
    delete obj.last_name 
    return obj 
} 

注:使用這​​種方法,你還應該設置選項{虛函數: true}爲toJSON。

userSchema.set('toJSON', {virtuals: true}); 
+1

嘗試你的答案並沒有因爲覆蓋的toJSON不包括虛擬領域的工作,所以我已經結束了刪除虛擬域和這樣做: 'userSchema.methods.toJSON = function(){let obj = this.toObject(); obj.last_name_initial = obj.last_name.substr(0,1).toUpperCase();刪除obj.last_name;返回obj;};' –

+0

是的...這也很好...將檢查有關虛擬選項的toJSON – ZeMoon