Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose schema recursion

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.

like image 785
nosbor Avatar asked Jan 29 '23 22:01

nosbor


1 Answers

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] });
like image 105
Tsvetan Ganev Avatar answered Jan 31 '23 15:01

Tsvetan Ganev