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); 

如果我使用普通查询,我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 

}

4

2 回答 2

3

从技术上讲,在 mongodb 中使用一个查询是不可能的,因为文档属于三个不同的集合。Mongoose 可能需要进行 5 次查询(虽然我认为 3 次就足够了,但我不确定 Mongoose 有多聪明)。

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

Cure.find()
  .populate('therapist')
  .populate('supervisor')
  .populate('parents')
  .populate('children')
  .exec(resultHandler);
于 2013-10-14T09:09:33.043 回答
0

您还可以将聚合与 $lookup 一起使用

Cure.aggregate([
   {
       "$lookup": {
          "from": "users",
         "localField": "therapist",
         "foreignField": "_id",
          "as": "therapist"
       }
   },
   {
       "$lookup": {
          "from": "users",
         "localField": "supervisor",
         "foreignField": "_id",
          "as": "supervisor"
       }
   }, ...
  ])
于 2017-08-01T11:57:37.673 回答