我遇到了一个问题:我需要从Mongoose返回的响应中删除一个_id字段。我使用lookup来连接来自两个集合的数据。我也用
aggregate({
    '$project': { _id: 0 }
})但这不包括顶级文档中的_id字段,而不是通过lookup嵌套的文档。
有什么想法吗?
这里有一个例子:比方说,我有两个模型:作者和书籍。作者模型返回的文档如下:
{ _id: '123', name: 'Jules Verne' }图书模型返回这样的文档:
{ _id: '555', title: 'Around the World in Eighty Days', author_id: '123' }使用猫鼬lookup与params:
{ 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 }来摆脱这个字段。但是如何从_id数组中的文档中删除wrote字段呢?
发布于 2017-05-17 10:35:41
你可以这样做:
//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);https://stackoverflow.com/questions/44020146
复制相似问题