我如何通过ID从另一个收集字段获取数据

时间:2019-01-18 13:20:49

标签: node.js mongodb mongoose mongodb-query

是这种情况。我有两个模型/模式。而且我想从出价模型中获取工作模型中的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”将出价模型中的出价输入到工作中,该怎么办?有可能吗?

1 个答案:

答案 0 :(得分:0)

由于您使用的是猫鼬,所以也只需填充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)