Mongoose从加入两个模型

时间:2017-11-27 10:27:21

标签: node.js mongodb

我有两个模型CRM模型和CRM STATUS模型。 _id和crm_id在两个模型中是相同的。任何id都可以有很多状态文件。我想在nodejs中找到CRM STATUS模型中每个id的最新更新状态。

CRM模型

        "_id" : ObjectId("5a16a6481dac972b9cf22978"),   /// join this 
        "updatedAt" : ISODate("2017-11-23T10:43:20.450Z"),
        "createdAt" : ISODate("2017-11-23T10:43:20.450Z"),
        "name" : "istiaque ahmad",
        "shop_name" : "soul dance",
        "address" : "dfsdfsd",
        "phone" : "01764199657",
        "email" : "nahid@gmail.com",
        "website" : "facebook.com",
        "comment" : "defdfsdfsdf",
        "interest" : "ddsfsdfsdf",
        "reference" : "dfsdfsdf",
        "__v" : 0

CRM状态

    "_id" : ObjectId("5a1a89041fe4313394da0db6"),
    "updatedAt" : ISODate("2017-11-26T09:27:32.725Z"), ///last updated
    "createdAt" : ISODate("2017-11-26T09:27:32.725Z"),
    "crm_id" : "5a1a48c5796ee01e90b618b6",  // join this 
    "name" : "nahid hasan",
    "shop_name" : "gift gallary",
    "status" : "dsadsdsada", /// find this 
    "__v" : 0

2 个答案:

答案 0 :(得分:0)

如果您在Shemas中使用“引用”,则可以“加入”某些模型。

查看Mongoose Populate Documentation

希望它有所帮助。

答案 1 :(得分:0)

可以尝试此查询

db.crm.aggregate([
  {
    $lookup: {
      from: "crmstatus",
      localField: "_id",
      foreignField: "crm_id",
      as: "status"
    }
  },
  {$unwind: {path: "$status", "preserveNullAndEmptyArrays": true}},
  {$sort: {"status.updatedAt": -1}},
  {
    $group: {
      _id: "$_id",
      name: {$first: "$name"},
      //... add fields as you need 
      status: {$first: "$status"}
    }
  }
])