node.js Moongodb 两个发现

问题描述

我上次纠结于如何在 nodejs 中放置两个 find 参数: 这是我当前的查询

userWithCompanies = await User.findById(userId).populate('companies');

但接下来我需要在其他部分制作搜索系统,例如:

companies = await Company.find({title: {$regex: `.*${search}.*`,$options: "i"}});

所以我尝试了这样的事情:

await User.findById(userId).populate('companies').find({title: {$regex: `.*${search}.*`,$options: "i"}});

但我刚刚收到错误

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

解决方法

您需要为 populate 方法提供 query condition
像这样:

const userWithCompanies = await User
  .findById(userId)
  .populate({
    path: 'companies',match: {
      title: {$regex: `.*${search}.*`,$options: "i"}
  });