如何向 return 嵌套对象中的信息发出 GET 请求,Mongoose Express

how to make a GET request to return the information in a nested object, Mongoose Express

我一直在尝试发出一个获取请求,该请求将 return 我的 userSchema 中嵌套对象中的所有对象。创建路由时,我通过 id 抓取用户,然后我尝试访问其中的 classwork 属性 这是一个嵌套对象,其中包含具有自己属性的 classwork 对象数组。我如何发出 GET 请求以仅显示用户的课业作业 JSON?

型号

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const ClassworkSchema = new Schema({
    name: String,
    time: Date,
    todo: String,
    isDone: false
});

const OutcomesSchema = new Schema({
    name: String,
    time: Date,
    todo: String, 
    isDone: false,
    isApproved: false
})

const MeetupSchema = new Schema({
    name: String,
    time: Date,
    location: String,
    attended: false
})
const UserSchema = new Schema({
    name: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
    date: {
      type: Date,
      default: Date.now
    },
    classwork: [ClassworkSchema],
    outcomes: [OutcomesSchema],
    meetups: [MeetupSchema],
  });



module.exports = User = mongoose.model('users', UserSchema);

GET 请求

  classworkRouter.get('/:userId/classwork', (req, res) => {
        User.findById(req.params.userId).populate('classwork').exec((err, data) => {
          if (err || !data) {
            res.status(404).json({error: 'user not found'});
          } else {
            res.json({data});
          }
        });
      });

你可以按照这个代码

  classworkRouter.get('/:userId/classwork', (req, res) => {
        User.findById(req.params.userId).populate('classwork' ,'classwork').exec((err, data) => {
          if (err || !data) {
            res.status(404).json({error: 'user not found'});
          } else {
            res.json({data});
          }
        });
      });

请检查documentation

这是可行的

classworkRouter.get('/:userId/classwork', (req, res) => {
  User.findById(req.params.userId).populate('classwork').exec((err, data) => {
    if (err || !data) {
      res.status(404).json({ error: 'user not found' });
    } else {
      res.json({ data: user.classwork });
    }
  });
});

这是相同的代码,但几乎没有改变我的风格

classworkRouter.get('/:userId/classwork', async (req, res) => {
  try {
    const user = await User.findById(req.params.userId).populate('classwork')
    if (!user) throw
    return res.status(200).json({ data: user.classwork })
  } catch (err) {
    res.status(404).json({ error: 'user not found' });
  }
})