首页 > 解决方案 > 如何从关系中获取数据以及存储在 Id 数组中的数据

问题描述

我有一个模型批次,其数据为

"id": {
      "type": "string",
      "id": true,
      "defaultFn": "uuidv4"
    },
    "batchType": {
      "type": "string",
      "required": true,
      "default": "COURSE"
    },
    "venue": {
      "type": "string",
      "required": true
    },

和另一位模特说预定洗澡

"batchesId": {
     "type": [
       "string"
     ],
     "required": true
   },

并创建了从批次模型到bookedBatches 模型的关系

 "relations": {
    "bookedBatches": {
      "type": "referencesMany",
      "model": "bookedBatches",
      "foreignKey": "batchesId",
      "primaryKey": "id"
    }
  }

现在我想要所有带有预订详细信息的批次,这些批次在批次模型的预订详细信息中存储为 Id 数组


let reqObject = {
                    "where": {
                        "and": [{
                            userId: userId,
                            isActive: true
                        }]
                    },
                    "order": "createdAt DESC",
                    include: [
                        {{
                            relation:"bookedBatches"}}]
}


Batches.find(reqObject, (resError, resData) => {
                    if (resError) {
                        return cb(new HttpErrors.BadRequest(resError, {
                            expose: false
                        }))
                    }
                    return cb(null, resData);
                })

但我没有得到任何价值,任何人都可以帮助通过关系获得价值

谢谢你!

标签: mongodbforeign-keysrelationshiploopback

解决方案


我改进了你的代码。请试试这个

 let reqObject = {
  "where": {
    "and": [{
      userId: userId,
      isActive: true
    }]
  },
  "order": "createdAt DESC",
  include: [
    {
      relation: "bookedBatches",
      scope: { fields: ["id","batchesId"] }
    }
  ]
}


Batches.find(reqObject, (resError, resData) => {
  if (resError) {
    return cb(new HttpErrors.BadRequest(resError, {
      expose: false
    }))
  }
  return cb(null, resData);
})

推荐阅读