首页 > 解决方案 > 如何通过 id 从另一个集合字段获取数据

问题描述

所以这就是这种情况。我有两个模型/模式。我想bid从投标模型中获取我的工作模型中的字段

这是我使用邮递员“发布”出价模型时的示例:

{
  "price": "8.770.000",
  "negotiation": "this is just example",
  "job" :"5c4192f5da1c3619f4089f5e" //this is job_id
}

当我尝试“获取”工作模型时,结果如下:

{
  "id": "5c4192f5da1c3619f4089f5e",
  "owner": {
    "id": "5be541622a228a231c6769c2",
    "username": "ceka",
    "rating": 0,
  },
  "title": "create website",
  "description": "this is just description",
  "category": "programming",
  "budget": "2.000.000",
  "remote": true,
  "bid": []
}

出价为空

投标型号:

const bidderSchema = new Schema({
  user: {
   type: Schema.ObjectId,
   ref: 'User',
   required: true
  },
  job: {
   type: Schema.ObjectId,
   ref: "Job",
   required: true
  },
  price: {
   type: String
  },
  negotiation: {
   type: String
  }
}

和工作模式:

const jobSchema = new Schema({
 owner: {
  type: Schema.ObjectId,
  ref: 'User',
  required: true
 },
 title: {
  type: String
 },
 description: {
  type: String
 },
 bid: [
  {
   type: Schema.ObjectId,
   ref: 'Bidder'
  }
 ]
}

路由器:

export const index = ({ querymen: { query, select, cursor } }, res, next) =>
Job.find(query, select, cursor)
 .populate('owner')
 .then((jobs) => jobs.map((job) => job.view()))
 .then(success(res))
 .catch(next)

所以重点是我想通过'job_id'将投标模型中的投标转化为工作,我该怎么做?可能吗?

标签: node.jsmongodbmongoosemongodb-query

解决方案


由于您使用的是猫鼬,因此您也应该很好地填充该bid行,如下所示:

export const index = ({ querymen: { query, select, cursor } }, res, next) =>
Job.find(query, select, cursor)
 .populate('owner')
 .populate('bid')
 .then((jobs) => jobs.map((job) => job.view()))
 .then(success(res))
 .catch(next)

推荐阅读