如何基于对象查询mongodb以获取包含一个或多个相等属性的文档(搜索)

问题描述 投票:0回答:2

我试图弄清楚如何将搜索对象发布到mongo,并查找与搜索对象中所述的一个或多个属性匹配的所有文档。

例如,如果我发布了一个json对象,如下:

// searchObject
{
  "kind": "employee"
  "name": "casper",
  "email": "[email protected]"
}

我想从员工集合中获取包含"name": "casper""email":"[email protected]"或全部都包含的所有文档。

这是我到目前为止所拥有的。但我不知道如何遍历我的财产。

router.post('/search', async (ctx) => {
  const searchObject = Object.assign(ctx.request.body);
  const collection = searchObject.kind

  const result = await store[collection].find({
    $and: [{ searchObject }]
  })
  console.log('result', result)
})
node.js mongodb routes koa
2个回答
0
投票

尝试一下:

router.post('/search', async ctx => {
  const { kind, ...searchObject } = ctx.request.body;
  const collection = searchObject.kind;
  const conditions = Object.keys(searchObject).reduce((acc, key) => {
    acc.push({ [key]: searchObject[key] });
    return acc;
  }, []);

  const result = await store[collection].find({
    $or: conditions,
  });
  console.log('result', result);
});

0
投票

在缩减功能中添加if (key !== "kind")条件

router.post('/search', async ctx => {
const searchObject = ctx.request.body;
const collection = searchObject.kind;
const conditions = Object.keys(searchObject).reduce((acc, key) => {
    if (key !== "kind") acc.push({ [key]: searchObject[key] });
    return acc;
}, []);

const result = await store[collection].find({
    $or: conditions,
});
console.log('result', result); 
});
© www.soinside.com 2019 - 2024. All rights reserved.