0

I am having issue where the populate query is not fetching any results into an array and it simply returns an empty array. I have two models namely Thread and Reply. Thread will have a reply array which stores all the replies which refers to the Reply model.

Here is my Thread Schema, Reply Schema and the models:

var Schema = mongoose.Schema;

  var threadSchema = new Schema({
    _id: Schema.Types.ObjectId,
    board: {type: String, required: true},
    text: String,
    delete_password: String,
    created_on: Date,
    bumped_on: Date,
    reported: Boolean,
    replies: [{ type: Schema.Types.ObjectId, ref: 'Reply' }]
  });

  var replySchema = new Schema({
    thread: { type: Schema.Types.ObjectId, ref: 'Thread' },
    text: String,
    delete_password: String,
    created_on: Date,
    reported: Boolean
  });

  var Thread = mongoose.model('Thread', threadSchema);

  var Reply = mongoose.model('Reply', replySchema);

Below is my code that querys the Thread model that should list down all the replies associated with the thread.

app.route('/api/replies/:board')
    .get(function(req, res) {
      var board = req.params.board;
      var threadId = req.query.thread_id;
      Thread.findById(threadId)
            .populate("replies")
            .exec(function(err, data) {
             if (err) return console.error(err);
               console.log(data);
               res.json(data);
      })
    })

In the above code, the resplies is always an empty array, but it should populate the id of all the replies.

Can anyone please help me in sorting out this issue? My full code is here https://glitch.com/~sincere-overjoyed-cart

1 Answers1

0
app.route('/api/replies/:board')
    .get(function(req, res) {
      var board = req.params.board;
      var threadId = req.query.thread_id;
      Thread.findById(threadId)
            .populate("replies")
            .then( data => {
               console.log(data);
               res.json(data);
            }).catch( err => {
             return console.error(err);
         });
      })
    })

Suggestion: If you are not using board in query it should not be passed in the URL. Better you pass the theadId directly.

Nayan
  • 638
  • 6
  • 15