猫鼬填充不填充数组,并且始终返回空数组

时间:2020-06-11 17:54:49

标签: node.js mongoose populate

我遇到的问题是,填充查询未将任何结果提取到数组中,而只是返回了一个空数组。我有两个模型,即线程和回复。线程将具有一个回复数组,该数组存储引用了回复模型的所有回复。

这是我的线程模式,回复模式和模型:

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);

下面是我的代码,该代码查询线程模型,该模型应列出与该线程相关的所有答复。

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);
      })
    })

在上面的代码中,resplies始终是一个空数组,但应填充所有答复的id。

有人可以帮我解决这个问题吗? 我的完整代码在这里https://glitch.com/~sincere-overjoyed-cart

1 个答案:

答案 0 :(得分: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);
         });
      })
    })

建议:如果您未在查询中使用木板,则不应在URL中传递该木板。最好您直接传递theadId。