在我的名为Quotations的模型模式中,我有一个名为customer的字段,它的类型为ObjectId,我也定义了ref

customer: {
    type: Schema.Types.ObjectId,
    ref: "Customer",
  },

我try 了一个搜索功能,像这样通过客户的名字来获得报价,

const quotations = await Quotation.find({
      "customer.firstName": keyword,
})

我想不通为什么这不管用.有人能给我指出错误吗?谢谢

推荐答案

这是一个集合.我以为你有quotations个Collection 和customers个Collection .

  1. $lookup customers集合,并将每个Quotation.customer值与Customer._id值进行匹配.
  2. customer.firstNamecustomer.firstName02.
  3. $unwind新的customer字段,因为$lookup总是返回一个array.
const quotations = await Quotation.aggregate([
  {
    $lookup: {
      "from": "customers",
      "localField": "customer",
      "foreignField": "_id",
      "as": "customer"
    }
  },
  {
    $match: {
      "customer.firstName": keyword
    }
  },
  {
    $unwind: "$customer"
  }
])

HERE章一个工作的例子

Edit:

为了提高效率,在上面的示例中,我将$match级移到了$unwind级之前,因为如果你有很多结果,$unwind可能会很昂贵,所以通过首先使用$match,你在最后一级中将数字减少到$unwind.

另一种 Select 是首先搜索customers个集合.使用返回的结果构造一个由ObjectId组成的数组,并将这些数组传递给具有$infind以查找customer上的匹配项,如下所示:

const customers = await Customer.find({firstName: keyword});
const ids = customers.map((c) => c._id);
const quotations = await Quotation.find({
    customer: {
        $in: ids
    }
}).populate('customer');

最后,效率最低的是搜索quotations个集合,搜索具有customerspopulate个集合.从返回的结果中,您可以筛选customer.firstName个匹配项的数组,如下所示:

const docs = await Quotation.find({}).populate('customer');
const quotations = docs.filter((d) => d.customer?.firstName === keyword);

Javascript相关问答推荐

使用print This时, map 容器已在LeafletJS中初始化

类型脚本中只有字符串或数字键而不是符号键的对象

在JavaScript中声明自定义内置元素不起作用

使用JavaScript重新排序行

cypress中e2e测试上的Click()事件在Switch Element Plus组件上使用时不起作用

如何将innerHTML字符串修剪为其中的特定元素?

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

将数组扩展到对象中

钛中的onClick事件需要在两次点击之间等待几秒钟

回溯替代方式

在验证和提交表单后使用useNavigate()进行react 重定向,使用带有加载器和操作的路由

处理TypeScrip Vue组件未初始化的react 对象

MongoDB中的嵌套搜索

有没有办法通过使用不同数组中的值进行排序

使用createBrowserRoutVS BrowserRouter的Reaction路由

我怎样才能点击一个元素,并获得一个与 puppeteer 师导航页面的URL?

使用Perl Selify::Remote::Driver执行Java脚本时出错

Chrome上的印度时区名S有问题吗?

如何按区域进行过滤并将其从结果数组中删除?

使用重新 Select 和对象理解 Select 器备忘