Mongoose查询所有子文档

时间:2013-10-14 08:38:15

标签: javascript node.js mongodb mongoose database

他是我的计划,我想做一个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); 

如果我使用普通查询,我在输出中有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 
     

}

2 个答案:

答案 0 :(得分:3)

从技术上讲,在mongodb中使用一个查询是不可能的,因为文档属于三个不同的集合。 Mongoose可能不得不做五个查询(虽然我认为三个应该足够但我不确定Mongoose有多聪明)。

但是,如果您真正问的是如何仅使用一条mongoose指令获取子文档,则应该查看populate()

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

答案 1 :(得分:0)

您还可以将聚合与$ lookup

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