用NodeJS和Mongoose查询embedded式文档

我需要从mongodb查询以下数据:项目有很多区域,一个区域有很多链接

这里是数据:

{ "_id" : ObjectId( "4f26a74f9416090000000003" ), "description" : "A Test Project", "regions" : [ { "title" : "North America", "_id" : ObjectId( "4f26a74f9416090000000004" ), "links" : [ { "title" : "A Really Cool Link" } ] }, { "description" : "That Asia Place", "title" : "Asia", "_id" : ObjectId( "4f26b7283378ab0000000003" ), "links" : [] }, { "description" : "That South America Place", "title" : "South America", "_id" : ObjectId( "4f26e46b53f2f90000000003" ), "links" : [] }, { "description" : "That Australia Place", "title" : "Australia", "_id" : ObjectId( "4f26ea504fb2210000000003" ), "links" : [] } ], "title" : "Test" } 

这是我的模型设置:

 // mongoose var Link = new Schema({ title : String , href : String , description : String }); var Region = new Schema({ title : String , description : String , links : [Link] }); var Project = new Schema({ title : String , description : String , regions : [Region] }); mongoose.model('Link', Link); mongoose.model('Region', Region); mongoose.model('Project', Project); var Link = mongoose.model('Link'); var Region = mongoose.model('Region'); var Project = mongoose.model('Project'); 

我正在努力的查询返回一个单一的区域对象在ID上匹配。 我很好地返回所有的地区与他们各自的链接,但限制它只是一个地区的ID是一个问题。

这是我正在处理的破碎路线:

 app.get('/projects/:id/regions/:region_id', function(req, res){ Project.findById(req.param('id'), function(err, project) { if (!err) { project.regions.findById(req.params.region_id, function(err, region) { if (!err) { res.render('project_regions', { locals: { title: project.title, project: project } }); } }); } else { res.redirect('/') } }); }); 

我知道上述不会工作,因为“findById”返回的对象不响应findByID,但它说明了我正在尝试做什么。 我试图做一个自定义查询,但它总是返回整个文档,而不是我想要的单个区域。

我也尝试直接从区域模式查询,但是这不是返回任何结果。 我假设从Schema查询这是一个子文档,我将不得不根据上下文提供什么是父文档。

换句话说,以下内容不会返回包含数据的“区域”对象:

 app.get('/projects/:id/regions/:region_id', function(req, res){ Region.findById(req.params.region_id, function(err, region) { if (!err) { res.render('project_regions_show', { locals: { title: "test", region: region } }); } else { res.redirect('/') } }); }); 

感谢任何帮助。

我build议使用“projectId:ObjectId()”字段将区域提取到单独的集合中。 这可能会给你查询的查询灵活性。

bstar,

您可以使用query.select防止加载子文档:

即。

 Entity.find({ ... }) .select({childentities: 0}) //excludes childentities .exec(function(err, entities){ ... res.json({entities: entities}); });