2017-05-17 101 views
0

我遇到了一个问题:我需要从Mongoose返回的响应中删除_id字段。我使用lookup来连接来自两个集合的数据。此外,我使用猫鼬在搜索中排除字段

aggregate({ 
    '$project': { _id: 0 } 
}) 

但是,这不包括_id领域从顶层文件,而不是从文档,通过lookup嵌套。

任何想法?

下面是一个例子:假设我有两种模型:作者和书籍。作者模型返回记录是这样的:

{ _id: '123', name: 'Jules Verne' } 

书籍模型的回报,例如DOC:

{ _id: '555', title: 'Around the World in Eighty Days', author_id: '123' } 

使用使用参数猫鼬lookup

{ from: 'books', localField: '_id', foreignField: 'author_id', as: 'wrote' } 

我会得到这样的回答:

{ _id: '123', 
    name: 'Jules Verne', 
    wrote: [ 
    { _id: '555', title: 'Around the World in Eighty Days', author_id: '123' } 
    ] 
} 

我并不需要_id字段既不是作者也不是书籍。对于作者,我可以使用'$project': { _id: 0 }摆脱这个领域。但是,如何从wrote数组中的文档中删除_id字段?

回答

0

你可以这样说:

//for example you have User schema 
const userSchema = new mongoose.Schema({ 
    email: String, 
    name: String, 
    gender: String 
}); 

userSchema.methods.getPublicFields = function() { 
    return { 
    email: this.email, 
    name: this.name 
    }; 
}; 

const User = mongoose.model('User', userSchema); 
+0

更新我的问题有一个例子来阐明这个问题 –