如何设置路由以访问 mongodb 中的嵌套对象
How do I set up a route to access nested objects in mongodb
获取表单的路径设置正确并且returns something similar to this。在问题数组中,我存储了问题对象,但我不知道如何访问它们。我的代码目前看起来像:
router.route('/:post_id/:q_id')
.get(function (request, response)
{
forms.findById(request.params.post_id,function(error,form)
{
if (error)
{
response.send({error: error});
}
else
{
for (var i in form.questions)
{
if (form.questions[i] == request.params.q_id)
{
questions = form.questions[i];
response.json({singleQuestion: questions});
}
}
}
});
})
这个returnsthis
我想知道如何获取对象并读取对象中的字段。
您似乎正在尝试执行以下操作:
router.get('/:formId/:questionId', (req, res) => {
Form.findOne({
_id: req.params.formId,
questions: req.params.questionId
}).populate('questions').then(form => {
if (!form) {
return res.status(404).json({error: 'Form not found'});
};
res.json({
singleQuestion: form.questions.find(q => q._id.toString() == req.params.questionId)
});
}).catch(err => res.status(500).json({error: 'Internal error'}));
});
但是,这条路线似乎设置为检索给定表单的问题对象。对您的表单 'get' 请求进行以下修改可能会更聪明:
router.get('/form/:formId', (req, res) => {
Form.findById(req.params.formId).populate('questions').exec((err, data) => {
if (err || !data) {
res.status(404).json({error: 'Form not found'});
} else {
res.json({data});
}
});
});
看看 mongoose's docs for populate - 本质上,它会将 questionId 交换为问题对象本身。将其视为 application-side 连接。
获取表单的路径设置正确并且returns something similar to this。在问题数组中,我存储了问题对象,但我不知道如何访问它们。我的代码目前看起来像:
router.route('/:post_id/:q_id')
.get(function (request, response)
{
forms.findById(request.params.post_id,function(error,form)
{
if (error)
{
response.send({error: error});
}
else
{
for (var i in form.questions)
{
if (form.questions[i] == request.params.q_id)
{
questions = form.questions[i];
response.json({singleQuestion: questions});
}
}
}
});
})
这个returnsthis
我想知道如何获取对象并读取对象中的字段。
您似乎正在尝试执行以下操作:
router.get('/:formId/:questionId', (req, res) => {
Form.findOne({
_id: req.params.formId,
questions: req.params.questionId
}).populate('questions').then(form => {
if (!form) {
return res.status(404).json({error: 'Form not found'});
};
res.json({
singleQuestion: form.questions.find(q => q._id.toString() == req.params.questionId)
});
}).catch(err => res.status(500).json({error: 'Internal error'}));
});
但是,这条路线似乎设置为检索给定表单的问题对象。对您的表单 'get' 请求进行以下修改可能会更聪明:
router.get('/form/:formId', (req, res) => {
Form.findById(req.params.formId).populate('questions').exec((err, data) => {
if (err || !data) {
res.status(404).json({error: 'Form not found'});
} else {
res.json({data});
}
});
});
看看 mongoose's docs for populate - 本质上,它会将 questionId 交换为问题对象本身。将其视为 application-side 连接。