【问题标题】:Mongoose one query for all sub documents猫鼬一次查询所有子文档
【发布时间】:2013-10-21 18:56:58
【问题描述】:

这是我的方案,我想做一个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 

}

【问题讨论】:

标签: javascript node.js mongodb mongoose database


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 它工作!!!!但仅适用于儿童,您认为为什么?另一个是 Null
    • OK ok .... 如果在数据库中 objectId 没有数据或 objectIdNull /b> 不正确
    猜你喜欢
    • 2015-06-26
    • 2017-06-01
    • 2019-10-19
    • 2014-03-21
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多