【问题标题】:How to filter documents on mongodb based on reference populated subdocuments?如何根据参考填充的子文档过滤 mongodb 上的文档?
【发布时间】:2019-09-15 03:17:03
【问题描述】:

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

这是我的模型

// 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 和/或 [{...SomeObject}, {...SomeOtherObject}]Blog.other 的博客的用户

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    看看 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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2018-08-17
      • 2019-08-04
      • 2015-07-06
      • 1970-01-01
      • 2018-01-26
      • 2011-01-30
      相关资源
      最近更新 更多