如何填充嵌套查询

How to Populate nested queries

本文关键字:嵌套 查询 填充 何填充      更新时间:2023-09-26

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

我的目标是通过调用主User关注的所有用户的所有最新文章来生成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. 按userID搜索并获得以下列表
  2. 填充那些关注者最近的文章

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

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

如有任何帮助,我们将不胜感激。

您需要两个查询。

第一个查询是您已经找到并需要的查询(获取以下列表)。您基本上需要一个由以下ID组成的数组,然后从这个用户数组中请求所有文章:

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

希望对有所帮助