【问题标题】:How to Populate nested queries如何填充嵌套查询
【发布时间】:2015-04-08 08:39:41
【问题描述】:

我有一个典型的 Node.js 项目 - Express - Mongoose - MongoDB

我的目标是通过调用主要用户关注的所有用户的所有最新文章来生成News 提要。

用户模型

var UserSchema = new Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  email: String,
  articles : [{ type: Schema.Types.ObjectId, ref: 'Article' }],
  follows: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  followers: [{ type: Schema.Types.ObjectId, ref: 'User' }]
});

文章模型

var articleSchema = new Schema({
  _userID: { type: Schema.Types.ObjectId, ref: 'user' },
  url: String,
  summary: String,
  title: String,
  content: String,
  image_url: String,
});

问题:

我正在尝试编写一个执行以下操作的猫鼬查询

  1. 按用户 ID 搜索并获取关注列表
  2. 填充这些关注者最近的文章

我可以弄清楚如何填充以下内容,但我不知道如何填充以下受人尊敬的文章并按时间顺序返回它们(最近>最旧)

    exports.getFeed = function(req, res) {
        var id = mongoose.Types.ObjectId(req.params.id);
        // mongoose query goes here
    };

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您需要两个查询。

    第一个查询是您已经找到并且无论如何都需要的查询(获取以下列表)。 您基本上需要一个包含以下 ID 的数组,然后从该用户数组中请求所有文章:

    .where('_userID').in(arrayOfFollowIDs)

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2015-12-06
      • 2019-08-10
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      相关资源
      最近更新 更多