猫鼬填充并通过填充字段进行搜索

时间:2019-08-10 23:33:39

标签: javascript node.js mongodb mongoose

我正在尝试对一个引用另一个集合的字段进行简单搜索。说我有发票的示例集合,其中引用了一个名为client的集合。因此示例架构如下所示:

const invoiceSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  amount: {
    type: Number,
    required: true
  },
  client: {
    type: Schema.Types.ObjectId,
    ref: 'Client'
  },
}

然后我有这样的客户端架构:

const clientSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  }
}

我要做的是查询发票架构并在客户端中搜索名称字段。

我尝试使用find和match进行填充,但是这只会返回整个发票集合,并且所有发票的客户字段均为空:

const q = new RegExp(req.body.q, 'i');

invoices = await Invoice.find().populate({
    path: 'client',
    match: {
      name: q
    }
  });

那么我应该如何用猫鼬搜索填充的字段?

0 个答案:

没有答案