【问题标题】:How to fetch specific fields of a sub-document population in mongoose如何在猫鼬中获取子文档群体的特定字段
【发布时间】:2020-07-25 15:36:49
【问题描述】:

我有如下所述的用户模型和帖子模型(导入所需的库)

用户架构

const UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    post: [ mongoose.Types.ObjectId, ref: 'posts' ]
});

发布架构

const UserSchema = new mongoose.Schema({
    title: String,
    content: String,
    postedOn: Date
});

我想获取与用户 ID 相关的帖子。但我不想要整个 Post 文档作为回报。我只想要属性“标题”和“日期”
我尝试了命令:-

const posts = await User.findById(user_id).populate('post');

但它会返回整个集合。谁能告诉我如何从用户模型中仅获取帖子(子文档)的“标题”和“日期”属性?

【问题讨论】:

    标签: mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    猫鼬种群通过通常的field name syntax 允许特定的field selection

    const posts = await User.findById(user_id).populate('post', 'Title Date');
    

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 2016-07-30
      • 2016-12-17
      • 2017-04-26
      • 2014-10-30
      • 2019-10-16
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      相关资源
      最近更新 更多