You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用findOne()将文档字段拆分到两个嵌套对象中

解决方案

有两种方式可以实现你需要的返回格式:

方法一:MongoDB聚合查询(单次数据库操作)

用aggregate()代替findOne(),通过$project阶段直接在数据库层面重组字段结构,不需要额外前端处理:

const existingAggr = await Bus.aggregate([
  // 匹配原findOne的查询条件
  { $match: { busNo, date } },
  // 重组字段到目标结构
  {
    $project: {
      result: {
        _id: "$_id",
        busNo: "$busNo",
        city: "$city",
        agency: "$agency",
        date: "$date"
      },
      aggregates: {
        ticketPrice: "$ticketPrice",
        totalCollection: "$totalCollection",
        helper: "$helper",
        driver: "$driver"
      }
    }
  },
  // 只取第一个匹配的文档,对应findOne的行为
  { $limit: 1 }
])[0]; // 聚合返回数组,取第一个元素即为目标对象

方法二:JavaScript处理查询结果

如果坚持使用findOne(),可以在拿到查询结果后,通过对象解构重组出目标格式:

const res = await Bus.findOne(
  { busNo, date },
  { 
    _id:1, busNo:1, city:1, agency:1, date:1,
    ticketPrice:1, helper:1, driver:1, totalCollection:1
  }
);

if (res) {
  // 将Mongoose文档转为普通JS对象,方便解构操作
  const doc = res.toObject();
  // 解构拆分字段
  const { ticketPrice, totalCollection, helper, driver, ...resultFields } = doc;
  // 组装成目标格式
  const existingAggr = {
    result: [resultFields],
    aggregates: { ticketPrice, totalCollection, helper, driver }
  };
}

内容的提问来源于stack exchange,提问作者Roomi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:30:51