【问题标题】:Using ref in express js to make a relationship in mongodb在express js中使用ref在mongodb中建立关系
【发布时间】:2021-04-12 20:22:54
【问题描述】:

我试图在 node js express 应用程序中建立两个模型之间的关系。我使用世界 ref 来检索创建课程的用户的姓名,但是,当我在登录或注册后从用户创建课程时,它不会显示有关创建该课程的用户的任何信息。相反,它显示一个空的 [] 数组。我想显示创建该课程的用户全名。

课程模型中的用户参考:

  },
  creator: [
    {
      ref: "Users",
      type: mongoose.Schema.Types.ObjectId,
    },
  ],

我在这里尝试获取创建课程的用户:

//Get all courses
exports.getAllCourses = async (req, res) => {
  await Courses.find()
    .sort("-created")
    .populate("creator", "firstName lastName fullName")
    .exec((err, courses) => {
      if (err) {
        res.status(500).send({ message: error.message });
      } else {
        res.status(200).send({
          message: "All courses fetched successfully",
          result: courses,
        });
      }
    });
};

我在邮递员中得到的结果:

{
    "message": " All courses fetched successfully",
    "result": [
        {
            "creator": [], <----- Here I am getting the user as an empty array
            "_id": "606d0f4d6051bb308089b5d2",
            "courseCode": "Math202",
            "courseName": "Math linear algebra",
            "section": "001",
            "semester": 1,
            "__v": 0
        }

【问题讨论】:

    标签: node.js mongodb express crud rest


    【解决方案1】:

    .populate({ path: 'creator', model: 'Users', select: 'firstName lastName fullName' });

    【讨论】:

    • 我又得到了一个空数组。它不是这样工作的
    • .populate('creator') 如果您在数组中获取用户的所有记录,请尝试此操作,检查它是否填充以及您是否正确提供了参考
    • 也不工作。我在我的问题中包含了一个代码,该代码显示了我如何在课程模型中引用用户。你能检查一下吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多