猫鼬/mongoDb搜索中我需要未填充属性的值 [英] Mongoose / mongoDb search where I need values of unpopulated property

查看:108
本文介绍了猫鼬/mongoDb搜索中我需要未填充属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在用mongodb/mongoose进行搜索.我有一个发布文档,该发布文档有一个comment属性,其中包含评论IDS.此搜索的目的是收集今天添加了评论的所有用户帖子.

So I'm doing a search with mongodb / mongoose. I have a post document and this post document has a comments property which consists of comment IDS. The goal of this search is to gather all the user's posts where a comment was added today.

我找不到任何帖子,因为我正在搜索comments.created_date,并且此属性尚不存在,因为我在comments属性的数组中只有注释IDS.

I can't find any posts because I am searching for comments.created_date and this property doesn't exist yet since I only have comment IDS in the array of the comments property.

如何填充"此数组,以便找到添加了评论的帖子?

How can I 'populate' this array so that I can find the posts that had comments added?

代码:首先,我们生成这一天开始的Date对象.然后我们搜索帖子.在这里,我谈论的是第一个$ or情况:comment.created_date不起作用,因为此属性由注释ID组成.如何获得今天发表评论的用户帖子?

 // Generate the actual time
    const todayForEvent = moment().startOf('day')
      .utc().toDate();



    const posts = await Post.find({

        $or: [{
        // From this user...
        $and: [
          // Find normal posts that has comments (recent interactions)
          { _posted_by: userId },
          { comments: { $exists: true, $ne: [] } },
          { 'comments.created_date': { $gte: todayForEvent } }
        ]
      }, {
        $and: [
          // Find tasks due to today
          { 'task._assigned_to': userId },
          { 'task.due_to': { $in: [today, tomorrow] } }
        ]
      }, {
        $and: [
          // Find events due to today
          { 'event._assigned_to': userId },
          { 'event.due_to': { $gte: todayForEvent, $lt: todayPlus48ForEvent } }
        ]
      }]
    })
      .sort('event.due_to task.due_to -comments.created_date')
      .populate('_posted_by', 'first_name last_name profile_pic')
      .populate('task._assigned_to', 'first_name last_name')
      .populate('event._assigned_to', 'first_name last_name')
      .populate('_group', 'group_name group_avatar')
      .populate('_liked_by', 'first_name last_name');

    console.log('POSTS', posts);

帖子模型

const mongoose = require('mongoose');

const { Schema } = mongoose;

const PostSchema = new Schema({
  content: {
    type: String,
    trim: true
  },
  _content_mentions: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  type: {
    type: String,
    required: true,
    enum: ['normal', 'event', 'task']
  },
  _liked_by: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  comments_count: {
    type: Number,
    default: 0
  },
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'Comment'
  }],
  _group: {
    type: Schema.Types.ObjectId,
    ref: 'Group',
    required: true
  },
  _posted_by: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  task: {
    due_to: {
      type: String,
      default: null
    },
    _assigned_to: {
      type: Schema.Types.ObjectId,
      ref: 'User'
    },
    status: {
      type: String,
      enum: ['to do', 'in progress', 'done']
    }
  },
  event: {
    due_to: {
      type: Date,
      default: null
    },
    _assigned_to: [{
      type: Schema.Types.ObjectId,
      ref: 'User'
    }]
  },
  created_date: {
    type: Date,
    default: Date.now
  },
  files: [{
    orignal_name: {
      type: String,
      default: null
    },
    modified_name: {
      type: String,
      default: null
    }
  }]
});

const Post = mongoose.model('Post', PostSchema);

module.exports = Post;

评论模型

const mongoose = require('mongoose');
const moment = require('moment');

const { Schema } = mongoose;

const CommentSchema = new Schema({
  content: {
    type: String,
    trim: true
  },
  _content_mentions: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  created_date: {
    type: Date,
    default: moment().utc().toDate()
  },
  _commented_by: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  _post: {
    type: Schema.Types.ObjectId,
    ref: 'Post',
    required: true
  }
});

const Comment = mongoose.model('Comment', CommentSchema);

module.exports = Comment;

推荐答案

由于必须使用注释created_date字段过滤文档,因此必须从注释集合开始汇总,而不要发布并加入posts使用 $lookup 聚合

Since you have to filter your documents with the comments created_date field then you must start your aggregation with the comments collection instead of post and join the posts with the $lookup aggregation

const todayForEvent = moment().startOf('day').utc().toDate()

db.comments.aggregate([
  { "$match": { "created_date": { "$gte": todayForEvent } }},
  { "$lookup": {
    "from": "posts",
    "localField": "_id",
    "foreignField": "comments",
    "as": "posts"
  }},
  { "$unwind": "$posts" },
  { "$replaceRoot": { "newRoot": "$posts" }}
])

这篇关于猫鼬/mongoDb搜索中我需要未填充属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆