首页 > 解决方案 > 如何根据参考填充的子文档过滤 mongodb 上的文档?

问题描述

我正在尝试根据填充的子文档来获取文档。

这是我的模型

// User model

    var UserSchema = new mongoose.Schema({
     username: {type: String, required: true, trim: true},
     firstName: {type: String, required: true, lowercase: true},
     lastName: {type: String, required: true, lowercase: true},
     phone: {type: String, required: false},
     email: {type: String, required: true},
     password: {type: String, required: true},
     blogs: {type: mongoose.Schema.Types.ObjectId, ref: 'Blogs'}
    }, {timestamps: true});


// Blog Model

    var BlogSchema = new mongoose.Schema({
     description: String,
     tags: [String],
     other: [Object],
    }, {timestamps: true});

这就是我抓取文件的方式

  fetchAllByFilter: async function(req, res) {
      try {
          let result = await Users.find({}).populate('blog');
          return res.status(200).send(result);
      }  catch (err) {
          return res.status(200).send({error: err});
      }
    },

现在我的主要问题是,我将如何根据用户的博客引用文档来获取用户?

例如,查找具有Blog.tags“食物”、“汽车”、“电影”和/Blog.other[{...SomeObject}, {...SomeOtherObject}]

标签: node.jsmongodbmongoose

解决方案


查看 mongo docs match an array,您可以制作一个有点像这样的实用函数......

async function findByTag(tag) {
    const blogIds = await Blog.find({ tags: tag }).select("_id");

    const users = await User.find({
        blogs: { $in: blogIds.map((blog) => blog._id) }
    }).populate("blog");
}

推荐阅读