我有一个前端在React和后端在express和node。
从FE我正在调用服务器上的API:
const { data: autotaskItems } = useApiCall({
url: `api/endpoint`,
method: 'post',
payload: {
filter: {
_id: {
$in: ["id1","id2"],
},
},
},
});
在服务器上:
router.post('/config-items/find', async (req, res) => {
const { filter } = req.body
// ConfigItem.find({ ...filter })
// .then(result => {
// res.status(200).json({ success: true, data: result });
// })
ConfigItem.aggregate([
{ $match: { ...filter }
}])
.then(result => {
res.status(200).json({ success: true, data: result });
})
但这不起作用。我发现聚合并不"支持"。自动将ObjectId转换为字符串。如果我像上面那样使用find()和spread过滤器,这将工作得很好。但是,我确实需要使用聚合,因为我也有几个查找。
有人能帮忙吗?此外,如果可能的话,我想保持结构与传播过滤器对象匹配
谢谢
根据@Martinez的回答,这是通过以下方式解决的:
又好又简单:-)
ConfigItem.aggregate([{
"$addFields": {
"_id": {
"$toString": "$_id"
}
}
},
//rest of the query