我创建了一个post Schema,实现注释和评论回复模式有困难,因为您无法预测一个评论回复有多少次有它自己的回复。
我用的是猫鼬和快车。
那么,如何实现这种模式设计呢?
发布于 2020-11-15 13:12:27
我认为您正在寻找这样的东西,您在这里引用注释模式中的注释。
在调用.find()时,我添加了一个中间件来预填充回复数组。您可以为其他调用(如.findOne()等)添加更多中间件。
const mongoose = require("mongoose");
const commentSchema = mongoose.Schema(
{
comment: {
type: String,
required: true
},
author: { // To reference the user that left the comment. If needed
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
replies:[{type: Schema.Types.ObjectId, ref: "Comment"}] // Array of comment replies
},
{
timestamps: true,
}
);
// Middleware to populate the replies when you call `find()`
commentSchema.pre('find', function() {
this.populate('replies');
});
module.exports = mongoose.model('Comment', commentSchema);您可以在这篇文章上做更深入的工作,这将向您展示如何在返回注释等时预先填充答复字段。
https://www.makeschool.com/academy/track/standalone/reddit-clone-in-node-js/comments-on-comments
https://stackoverflow.com/questions/64844567
复制相似问题