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
  • Don't need to use exec if the query is find query. It should work Commented Jun 11, 2020 at 18:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But even then it should work right? It does nothing with the querying part.
Tried your suggestion and your answer, but still it is not working for me. Really getting worse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.