Mongoose一次查询所有子文档

3
这是我的方案,我想做一个单一的“查询”,并获取所有文档和所有对象的文档。
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 

}


1
你是否在寻找http://mongoosejs.com/docs/populate.html? - WiredPrairie
2个回答

3

从技术上讲,在mongodb中不可能通过一个查询来完成此操作,因为文档属于三个不同的集合。Mongoose可能需要执行五个查询(尽管我认为三个查询就足够了,但我不确定Mongoose有多聪明)。

但是,如果您真正想知道如何仅使用一个mongoose指令获取子文档,则应查看populate()

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

它工作了!!!但只适用于儿童,你认为为什么??对于其他人来说是空值 - jay
好的,如果在数据库中,该objectId没有数据或者该objectId不正确,则为Null。 - jay

0

你也可以使用 $lookup 与聚合一起使用

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接