2012-01-31 80 views
2

內嵌文件中我需要從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('/') 
    } 
    }); 
}); 

得到任何幫助。

+0

我不得不通過ObjectId去掉區域模型引用它。這張票據解釋了我使用的填充功能:http://stackoverflow.com/questions/7810892/node-js-creating-relationships-with-mongoose – bstar 2012-01-31 19:55:34

回答

0

我建議使用「projectId:ObjectId()」字段將區域提取到單獨的集合中。這可能會給你查詢的查詢靈活性。

+0

這是最有意義的。我沒有意識到文檔查詢總是返回整個文檔。謝謝。 – bstar 2012-01-31 15:05:08

1

bstar,

您可以防止子文件加載使用query.select:

即。

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