【问题标题】:Mongoose exclude fields in lookupMongoose 在查找中排除字段
【发布时间】:2017-10-16 15:19:12
【问题描述】:

我遇到了一个问题:我需要从 Mongoose 返回的响应中删除 _id 字段。我使用lookup 来连接来自两个集合的数据。我也用

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

但这不包括顶级文档中的 _id 字段,而不是文档,通过 lookup 嵌套。

有什么想法吗?

这是一个示例:假设我有两个模型:作者和书籍。作者模型返回这样的文档:

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

Books 模型返回这样的文档:

{ _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 字段?

【问题讨论】:

    标签: mongoose aggregate


    【解决方案1】:

    你可以这样做:

    //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);
    

    【讨论】:

    • 用一个例子更新了我的问题以澄清问题
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2015-01-10
    • 2013-01-09
    • 2019-10-14
    • 2018-02-03
    • 2020-11-27
    相关资源
    最近更新 更多