【发布时间】:2021-04-19 07:06:17
【问题描述】:
我一直在尝试发出一个 get 请求,该请求将返回 My 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});
}
});
});
【问题讨论】:
-
您是否难以使用 Postman 检查收到的 get 请求响应?
-
如果您只想将选定的数据发送给用户,您可以在填充后使用 .select('fieldName')
-
邮递员正在返回整个用户信息,但我只想要课业对象数组而不是所有用户信息。
标签: javascript express mongoose get postman