代码之家  ›  专栏  ›  技术社区  ›  tilly

Mongoose/MongoDB搜索,其中我需要未填充属性的值

  •  1
  • tilly  · 技术社区  · 6 年前

    所以我用mongodb/mongoose进行搜索。我有一个日志文档,这个日志文档有一个由注释ID组成的注释属性。此搜索的目标是收集今天添加了评论的所有用户的帖子。

    我找不到任何文章,因为我正在搜索comments.created_date,而且此属性还不存在,因为我在comments属性的数组中只有comment id。

    如何“填充”此数组,以便找到添加了注释的文章?

    代码:首先生成今天开始的日期对象。然后我们搜索这些帖子。这里,我讨论的是第一个$or case:comments.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;
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    因为你必须用注释过滤你的文档 created_date 字段,则必须使用注释集合而不是Post开始聚合,然后加入 posts $lookup 聚集

    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" }}
    ])