我试图弄清楚如何将搜索对象发布到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)
})
尝试一下:
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);
});
在缩减功能中添加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);
});