Before everyone tells me I can't call a const before initializing, I do know that. But I think this is the simplest way to render the concept I have in mind, ( where any subdocument within the replies array also has the same schema as the parent, and documents within the replies array of those subdocuments also having the same schema ). I would really appreciate anyone's input.
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);
Since a const can't be called before initialization, to fix this issue the parent schema should be called on the children array after initialization the code below:
commentSchema.add({ replies: [commentSchema] })
The final result should look like this:
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] })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.