[英]How to create a dynamic nested mongoose document with the same schema on multiple levels
在所有人告诉我在初始化之前我不能调用 const 之前,我确实知道这一点。 但我认为这是呈现我想到的概念的最简单方法(其中回复数组中的任何子文档也具有与父文档相同的架构,并且这些子文档的回复数组中的文档也具有相同的架构)。 我真的很感激任何人的意见。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
replies: [commentSchema]
});
module.exports = mongoose.model("comment", commentSchema);
由于在初始化之前无法调用 const,因此要解决此问题,应在初始化后在子数组上调用父模式,代码如下:
commentSchema.add({ replies: [commentSchema] })
最终结果应如下所示:
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const commentSchema = new mongoose.Schema({ content: String, createdAt: { type: Date, default: Date.now }, score: { type: Number, default: 1 }, username: { type: String, lowercase: true }, parent: { type: Schema.Types.ObjectId, ref: 'comment' }, replyingTo: String, }); commentSchema.add({ replies: [commentSchema] })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.