当 Mongoose 中的数组中有两个对象时,如何填充它们?

问题描述 投票:0回答:1

router.get('/mypage/myreport-comment', catchAsync( async(req, res) => {
    const { id } = req.user;
    const { page } = req.query;

    const totalPost = await Comment.find({'reports.user': id}).populate('reports.user'); //.countDocuments({});

    let { startPage, endPage, hidePost, maxPost, totalPage, currentPage } = myPageCommentPaging(page, totalPost);
    const comments = await Comment.find({reports:{user:id}, isDeleted: false}).sort({ createdAt: -1 }).skip(hidePost).limit(maxPost).populate('author').populate('board');
    
res.render('users/myReportComment', {comments, startPage, endPage, totalPage, currentPage, maxPost})

}));
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');

const UserSchema = new Schema({
    nickname: {
        type: String,
        required: true,
        unique: true
    },
    role: {
        type: String,
        enum: ['user', 'master'],
        default: 'user'
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    isWithdrawn: {
        type: Boolean,
        default: false
    }
});

UserSchema.plugin(passportLocalMongoose, {usernameField: 'email'});

module.exports = mongoose.model('User', UserSchema);
const mongoose = require('mongoose');
const Schema = mongoose.Schema;


const CommentSchema = new Schema({
    body: String,
    createdAt: {
        type: Date,
        default: Date.now
    },
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    board: {
        type: Schema.Types.ObjectId,
        ref: 'Board'
    },
    likes: [
        {
            type: Schema.Types.ObjectId,
            ref: "User"
        }
    ],
    parentComment: {
        type: Schema.Types.ObjectId,
        ref: "Comment"
    },
    hasReply: {
        type: Boolean,
        default: false
    },
    isDeleted: {
        type: Boolean,
        default: false
    },
    reports: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: "User"
            },
            reportedAt: {
                type: Date,
                default: Date.now
            }
        }
    ]
});

module.exports = mongoose.model('Comment', CommentSchema);

我正在尝试查找报告字段中存在特定用户的所有 Comment 对象。

我想填充“报告”字段中的“用户”字段,但方法

.populate( 'reports.user' )
不起作用。我该怎么办?

我尝试以各种方式输出代码

const totalPost = await Comment.find({'reports.user': id}).populate('reports.user');
,但是
totalPost
要么输出空数组,要么以格式
reports: [[object]]
显示。

这可能听起来很尴尬,因为英语不是我的母语。

node.js mongodb express mongoose mongoose-populate
1个回答
0
投票

我认为你应该使用

const totalPost = await Comment.find({
      'reports': {
        $elemMatch: {
          'user': id
        }
      }
    });

因为 $elemMatch 运算符对于在对象数组中查找数组中至少有一个元素非常有用。

了解更多信息:https://www.mongodb.com/docs/manual/reference/operator/query/elemMatch/

© www.soinside.com 2019 - 2024. All rights reserved.