Is it possible to make an recursion in Mongoose?
For example, I want to create nested comments.
Let's consider following example:
commentSchema = new mongoose.Schema({
comment : String,
author : String,
answers : [commentSchema] // ReferenceError: commentSchema is not defined
})
productSchema = new mongoose.Schema({
name : {type: String, required: true},
price : Number,
comments : [commentSchema]
})
In SQL it's quite easy to achieve that with keys.
First what come to my mind is to add parent field in commentSchema which will point to the comment which it is answering, but in that case, if the comments are just a simple objects in array, they do not have ids generated, so this solution cannot be done in current design.
Second solution that come to my mind is to create a separate table for comments, and then they will have their own ids, but is it a good way to do go in mongodb? I mean it starts looking very similar to the SQL tables design.
You can use the Schema.add()
method. First you define your schema without the recursive property. After you have assigned the newly created schema to the commentSchema
variable, you can set it as a property type by calling the add()
method.
const commentSchema = new mongoose.Schema({
comment: String,
author: String
});
commentSchema.add({ answers: [commentSchema] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With