Mongoose排除查找中的字段

时间:2017-05-17 09:00:06

标签: mongoose aggregate

我遇到了一个问题:我需要从 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' }

使用带有参数的mongoose 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 }删除此字段。但是,如何从_id数组中的文档中删除wrote字段?

1 个答案:

答案 0 :(得分: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);