猫鼬对象填充时返回未定义

时间:2020-03-06 13:35:50

标签: javascript node.js mongodb mongoose

我正在努力解决一些问题。我想做的是在评论中填充用户。

用户架构:

const userSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true
  }
});

评论架构:

const commentSchema = mongoose.Schema({
  comment:{
    type: String
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
});

我已经创建了用户和评论。当我尝试找到两个对象时,一切都很好。

评论:

Comment.find({}).exec((err, comments) => {
  console.log(comments);
});

输出:

[
 {
   _id: 5e62472d5f593f3c642ee1e5,
   comment: 'something',
   user: 5e624522366d8c4150278a64,
   __v: 0
 }
]

用户:

User.find({}).exec((err, users) => {
  console.log(users);
});

输出:

[
 {
  _id: 5e624522366d8c4150278a64,
  username: "SomeBodY", 
  password: "$2a$10$nm5BJ7zeI1tet3UEzcakf.8xoTgV/Yti5l1EKNg5inxiehevUlGRm"
 }
]

问题是,当我使用.populate('user')Comment模型时,它将在控制台中以undefined的形式返回注释。我尝试了不同的方法,甚至删除了数据库,但都没有成功。

这是发生这种情况的路线

// Route To Single Project
router.get('/:projectId', (req, res) => {
  const requestedProjectId = req.params.projectId;
  Project.findById({_id: requestedProjectId}).populate('image_file').exec((err, project) => {
    Rating.find({projectId: requestedProjectId}, (err, ratings) => {
      Rating.countDocuments({projectId: requestedProjectId}, (err, count) => {
        Comment.find({projectId: requestedProjectId}).populate('user').exec((err, comments) => {
          console.log(comments)
          if(err) return next(err);
          res.render('project', { ... });
        });
      });
    });
  });
});

1 个答案:

答案 0 :(得分:0)

实际上,您的填充代码为true。

获得空注释的原因是因为此Comment.find({projectId: requestedProjectId})似乎返回空。因此,只需检查您的请求参数即可。

另外,为了摆脱回调地狱,您可以像这样使用async / await重写路由。

router.get("/:projectId", async (req, res) => {
  const requestedProjectId = req.params.projectId;

  try {
    const project = await Project.findById({ _id: requestedProjectId }).populate("image_file");

    if (!project) {
      return res.status(400).send("Project not found, check your projectId");
    }

    const comments = await Comment.find({ projectId: requestedProjectId }).populate("user");
    console.log(comments);

    const ratings = await Rating.find({ projectId: requestedProjectId });

    const count = await Rating.countDocuments({ projectId: requestedProjectId });

    res.render("project", {
      project,
      comments,
      ratings,
      count
    });
  } catch (err) {
    console.log("Error: ", err);
    res.status(500).send("Something went wrong");
  }
});