【问题标题】:Mongo and mongoose $match _id in arrayMongodb 和 mongoose $match 数组中的 _id
【发布时间】:2022-11-30 00:06:56
【问题描述】:

我在 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() 和传播过滤器,这将工作得很好。但是,我确实需要使用聚合,因为我在那里也有几个查找。

任何人都可以帮忙吗?

另外,如果可能的话,我想通过传播过滤器对象来保持结构以进行匹配

谢谢

【问题讨论】:

标签: mongodb mongoose aggregate


【解决方案1】:

根据@Martinez的回答,这已通过以下方式解决:

漂亮而简单:-)

  ConfigItem.aggregate([{
    "$addFields": {
      "_id": {
        "$toString": "$_id"
      }
    }
  },
//rest of the query

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 2019-07-24
    • 2017-08-20
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2015-12-28
    • 2022-09-24
    • 2021-07-16
    相关资源
    最近更新 更多