内嵌文件中我需要从MongoDB中查询以下数据: 项目有许多地区,一个地区有很多链接查询用的NodeJS和猫鼬
这里的数据:
{ "_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回应,但它说明了我是什么试图去做。我试着做一个自定义查询,但它总是返回整个文档,而不是我想要的单个区域。
我也试过直接查询Region Schema,但是没有返回任何结果。我假设从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('/')
}
});
});
得到任何帮助。
我不得不通过ObjectId去掉区域模型引用它。这张票据解释了我使用的填充功能:http://stackoverflow.com/questions/7810892/node-js-creating-relationships-with-mongoose – bstar 2012-01-31 19:55:34