我正在使用mongodb和mongoose在Node.js中开发一个应用程序。我想从mongoose返回的对象数组中获取对象的索引,下面给出了数据,如何从详细信息中获取索引数据,其中记录包含特定的id,如
_id:5334032ad1c4d2d616ad3a47
实际问题是我正在渲染一个显示详细记录的单个嵌套记录数据的页面,该记录的id包含在我的网址中
http://localhost:3000/id-of-parent-course/id-of-nested-doc-in-details
我将所有数据传递到该页面因为我想访问详细记录的总数,可能是我这样做的方式是错误的你可以用答案纠正我
course:
{ __v: 1,
_id: 5334032ad1c4d2d616ad3a46,
updatedAt: Fri Mar 28 2014 13:14:07 GMT+0530 (IST),
createdAt: Thu Mar 27 2014 16:23:30 GMT+0530 (IST),
comments: [],
details:
[ { status: 'Core',
course_type: 'New',
_id: 5334032ad1c4d2d616ad3a47,
books: [Object],
course_content: [Object],
learning_outcomes: [Object],
objectives: [Object],
senate_approval_on: Fri Mar 14 2014 00:00:00 GMT+0530 (IST),
ac_approval_on: Wed Mar 19 2014 00:00:00 GMT+0530 (IST),
center_approval_on: Wed Mar 12 2014 00:00:00 GMT+0530 (IST),
focus_group_approval_on: Tue Mar 11 2014 00:00:00 GMT+0530 (IST),
effect_from: Tue Apr 01 2014 00:00:00 GMT+0530 (IST),
pre_requisite: 'Javascript',
offered_for: 'B.Tech',
structure: [Object],
department: 'ICT',
course_no: 12345,
title: 'Course 1' },
{ status: 'Core',
course_type: 'New',
_id: 533528472ad1706170b502b0,
books: [Object],
course_content: [Object],
learning_outcomes: [Object],
objectives: [Object],
senate_approval_on: Fri Mar 14 2014 00:00:00 GMT+0530 (IST),
ac_approval_on: Wed Mar 19 2014 00:00:00 GMT+0530 (IST),
center_approval_on: Wed Mar 12 2014 00:00:00 GMT+0530 (IST),
focus_group_approval_on: Tue Mar 11 2014 00:00:00 GMT+0530 (IST),
effect_from: Tue Apr 01 2014 00:00:00 GMT+0530 (IST),
pre_requisite: 'Javascript',
offered_for: 'B.Tech',
structure: [Object],
department: 'ICT',
course_no: 12345,
title: 'Course 1' } ] } }
答案 0 :(得分:0)
您必须迭代数组并保留索引,如:
var i=0,
found=false;
for(i = 0; i < course.details.length; i++) {
var detail = course.details[i];
if(detail._id === idYouReSearchingFor) {
found=true;
break;
}
}
if(found) //your index is on variable i