我有以下架构(CoffeeScript):
adSchema = new mongoose.Schema({
...
user : { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
...
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
})
userSchema = new mongoose.Schema({
username : String
email :
type : String
required : true
index :
unique : true
adverts : [{ type: mongoose.Schema.Types.ObjectId, ref: 'Advert' }]
},
{
toObject: { virtuals: true }
toJSON: { virtuals: true }
})
userSchema.virtual('screenname').get () ->
if this.username? then this.username else this.email.split('@')[0]+'@...'
然后我尝试获取一堆记录并填充用户:
getAdvertPage = (obj, fn) ->
page_size = 10
query =
tags : obj.tag
Advert.count query, (err, count) ->
Advert.find(query)
.sort(obj.sort)
.skip((obj.page-1)*page_size)
.limit(page_size)
.populate('user', 'screenname')
.exec (err, ads) ->
ads.lastPage = (obj.page-1)*page_size + page_size >= count
fn err, ads
但我只想要用户的屏幕名称,而不想要其他(这是一个虚拟字段)。但是,这会导致错误:
Cannot call method 'split' of undefined
如果我在填充中包含电子邮件,它可以正常工作,但我不想将电子邮件发送给客户端。有没有办法只填充一个虚拟字段?