2013-10-14 25 views
3

他是我的方案,我想做一個單獨的query並獲得all documents和所有對象的文檔。貓鼬一個查詢所有子文件

var CureSchema = mongoose.Schema({ 

      id:   Number, 
      therapist: {type:mongoose.Schema.Types.ObjectId, ref:'User'}, 
      supervisor: {type:mongoose.Schema.Types.ObjectId, ref:'User'}, 
      parents: {type:mongoose.Schema.Types.ObjectId, ref:'User'}, 
      children: {type:mongoose.Schema.Types.ObjectId, ref:'Child'}, 
      startate : Date, 
      endDate : Date, 
      deleted: Boolean, 
    }); 

    var Cure = mongoose.model('Cure', CureSchema); 

如果我使用正常的查詢,在輸出i'have objectId

{

 "id":0, 

    "therapist":ObjectId("5253cbd8d4fb240000000007"), 

    "supervisor":ObjectId("5253cc9fd4fb24000000000b"), 

    "parents":ObjectId("5253cbdfd4fb240000000008"), 

    "children":ObjectId("5253cb31d4fb240000000001"), 
    "deleted":false, 

    "startate": ISODate("2013-10-08T09:13:06.771Z"), 

"_id":ObjectId("5253cca2d4fb24000000000c"), 
"__v":0 

}

+1

您是否在尋找http://mongoosejs.com/docs/populate.html? – WiredPrairie

回答

3

從技術上講這是不可能的,在MongoDB中一個查詢做到這一點,因爲這些文件屬於三個不同的集合。貓鼬可能需要做五個查詢(雖然我認爲三個應該夠了,但我不確定貓鼬是多麼聰明)。

但是,如果您真正要問的是如何僅使用一條貓鼬指令獲取子文檔,則應該查看populate()

Cure.find() 
    .populate('therapist') 
    .populate('supervisor') 
    .populate('parents') 
    .populate('children') 
    .exec(resultHandler); 
+0

是的,我想知道 – jay

+0

它工作! 但只限於兒童,爲什麼在你看來?? 這是**空**爲其他 – jay

+0

好吧....它的**空**如果在數據庫中,** objectId **,沒有數據或** objectId **不正確 – jay

0

您也可以使用聚合以$查找

Cure.aggregate([ 
    { 
     "$lookup": { 
      "from": "users", 
     "localField": "therapist", 
     "foreignField": "_id", 
      "as": "therapist" 
     } 
    }, 
    { 
     "$lookup": { 
      "from": "users", 
     "localField": "supervisor", 
     "foreignField": "_id", 
      "as": "supervisor" 
     } 
    }, ... 
    ])