【发布时间】:2022-02-01 22:39:36
【问题描述】:
我有 2 个模型Comment 和 Report。
const mongoose = require('mongoose');
const CommentSchema = new mongoose.Schema(
{
content: {
type: String,
trim: true,
maxLength: 2048,
},
createdAt: {
type: Date,
default: Date.now,
},
parent: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
required: false,
},
replies: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
},
],
isReply: {
type: Boolean,
default: false,
},
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
CommentSchema.virtual('reportCount', {
ref: 'Report',
localField: '_id',
foreignField: 'comment',
justOne: false,
count: true,
});
CommentSchema.virtual('reportReplyCount', {
ref: 'Report',
localField: 'replies',
foreignField: 'comment',
justOne: false,
count: true,
});
module.exports = mongoose.model('Comment', CommentSchema);
Comment 具有字段回复,它是指向 Comment 模型的引用数组。用户可以报告评论,当发生这种情况时,新的报告文档会存储在报告集合中,并且它包含对该评论的引用和对用户的引用。我在评论架构中有 2 个虚拟属性,reportCount(显示该评论的报告数量)和 reportReplyCount(显示评论回复的报告数量)。现在 reportCount 可以完美运行,但 reportReplyCount 却不行。当我创建评论以及对该评论的回复时,它会显示回复数量而不是报告数量。我用谷歌搜索但找不到类似的东西。
const mongoose = require('mongoose');
const ReportSchema = new mongoose.Schema({
description: {
type: String,
trim: true,
required: true,
maxLength: 100,
},
reporter: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
comment: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
required: true,
},
});
module.exports = mongoose.model('Report', ReportSchema);
【问题讨论】:
标签: node.js express mongoose mongoose-schema mongoose-populate