引用另一个模型时猫鼬填充不起作用

问题描述

我一直在尝试在评论模型中引用用户模型。我已确保一切都已检查完毕,但仍然无法正常工作。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const commentSchema = mongoose.Schema({
  writer: {
    type: Schema.Types.ObjectId,ref: 'User'
  },postId: {
    type: String,},responseto: {
    type: Schema.Types.ObjectId,content: {
    type: String
  }

},{ timestamps: true })


const Comment = mongoose.model('Comment',commentSchema);

module.exports = { Comment }

在这里引用用户模型是因为我需要从中获取一些字段。

router.post("/saveComment",auth,(req,res) => {

  const comment = new Comment(req.body)

  comment.save((err,comment) => {
    if (err) return res.json({ success: false,err })
     
    //send newly saved comment inside parent cmp
    Comment.find({ '_id': comment._id })
      .populate('writer')
      .exec((err,result) => {
        if (err) return res.json({ success: false,err })
        return res.status(200).json({ success: true,result })
      })

  })

})

向该端点发出请求会返回结果,但会忽略我对用户模型的引用

{
    "success": true,"result": [
        {
            "_id": "60527698499c27244c9e9f4c","content": "Comment 1","createdAt": "2021-03-17T21:37:28.463Z","updatedAt": "2021-03-17T21:37:28.463Z","__v": 0
        }
    ]
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)