如何在嵌套对象内部使用populate函数。

huangapple go评论60阅读模式
英文:

How to use populate function inside a nested object

问题

在我的用户模式中,有一个字段如此定义。

courseTaken: [
    {
      course: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Course",
      },
      rating: {
        type: Number,
        min: 0,
        max: 5,
        default: 0,
        validate: {
          validator: function (v) {
            return Number.isInteger(v * 2);
          },
          message: "Rating can only be incremented by 0.5",
        },
      },
    },
  ], 

我正在创建一个路由,用户获取他所选课程。为了做到这一点,我使用了 populate。我像这样做:

exports.getClassroom = catchAsync(async (req, res, next) => {
  let t = await req.user.courseTaken.populate("course");
  const classroom = t.courseTaken;
  console.log(t);
  res.status(200).json({
    status: "success",
    classroom,
  });
  next();
});

但是,我收到了以下错误:

TypeError: req.user.courseTaken.populate is not a function
    at /Users/vedantamohapatra/msb-academy/api/controllers/userController.js:105:38
    at /Users/vedantamohapatra/msb-academy/api/utils/catchAsync.js:3:7
    at Layer.handle [as handle_request] (/Users/vedantamohapatra/msb-academy/api/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/vedantamohapatra/msb-academy/api/node_modules/express/lib/router/route.js:144:13)
    at /Users/vedantamohapatra/msb-academy/api/controllers/authController.js:95:3
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
英文:

In my user schema, there is a field as such.

courseTaken: [
    {
      course: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Course",
      },
      rating: {
        type: Number,
        min: 0,
        max: 5,
        default: 0,
        validate: {
          validator: function (v) {
            return Number.isInteger(v * 2);
          },
          message: "Rating can only be incremented by 0.5",
        },
      },
    },
  ], 

I was doing a route where the user getss the courses he has taken. To do this I was using populate. I was doing something like this:

exports.getClassroom = catchAsync(async (req, res, next) => {
  let t = await req.user.courseTaken.populate("course");
  const classroom = t.courseTaken;
  console.log(t);
  res.status(200).json({
    status: "success",
    classroom,
  });
  next();
});

But, I get the following error:

TypeError: req.user.courseTaken.populate is not a function
    at /Users/vedantamohapatra/msb-academy/api/controllers/userController.js:105:38
    at /Users/vedantamohapatra/msb-academy/api/utils/catchAsync.js:3:7
    at Layer.handle [as handle_request] (/Users/vedantamohapatra/msb-academy/api/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/vedantamohapatra/msb-academy/api/node_modules/express/lib/router/route.js:144:13)
    at /Users/vedantamohapatra/msb-academy/api/controllers/authController.js:95:3
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

答案1

得分: 1

错误的原因是您试图在数组上调用populate方法,而数组不是Mongoose模型。

您可以在Mongoose模型上使用populate方法,针对User模式,指定path选项以填充courseTaken字段。

您可以尝试以下代码:

exports.getClassroom = catchAsync(async (req, res, next) => {
  const user = await User.findById(req.user._id).populate('courseTaken.course');
  const classroom = user.courseTaken;
  res.status(200).json({
    status: "success",
    classroom,
  });
  next();
});
英文:

The reason for the error is that you are trying to call the populate method on an array, which is not a Mongoose model.

you can use the populate method on the Mongoose model for the User schema, and specify the path option to populate the courseTaken field.

You can try this code:

exports.getClassroom = catchAsync(async (req, res, next) => {
  const user = await User.findById(req.user._id).populate('courseTaken.course');
  const classroom = user.courseTaken;
  res.status(200).json({
    status: "success",
    classroom,
  });
  next();
});

huangapple
  • 本文由 发表于 2023年4月19日 17:26:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052865.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定