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

如何从MongoDB返回的嵌套对象中提取日期并打印到控制台?

解决MongoDB查询结果中date对象显示为[Object]并提取具体字段的问题

问题原因

控制台打印嵌套对象时,默认会简化显示为[Object],这是JavaScript控制台的默认行为,并非数据丢失,只需显式访问内部属性或调整打印方式即可查看完整内容。

解决方案

以下几种方式可实现提取并打印date中的day、month、year:

方式1:遍历结果显式访问date属性

修改查询回调代码,遍历处理后的结果,直接访问date的各个字段:

collection.find({ name: "Tom" }).toArray(function(err, results) {
  if (err) return console.log(err);
  
  // 遍历每个用户的categories
  results.forEach(user => {
    user.сategories.forEach(cat => {
      const { cost, date } = cat.products;
      console.log(`商品价格:${cost}`);
      console.log(`日期:${date.year}年${date.month}月${date.day}日`);
    });
  });
  
  client.close();
});

方式2:映射阶段直接拆分date字段

如果需要将date的字段单独提取出来,可以在map阶段提前处理:

collection.find({ name: "Tom" }).toArray(function(err, results) {
  if (err) return console.log(err);
  
  let res = results.map(user => 
    user.сategories.map(cat => ({
      cost: cat.products.cost,
      day: cat.products.date.day,
      month: cat.products.date.month,
      year: cat.products.date.year
    }))
  );
  
  console.log(res); // 此时会直接显示拆分后的日期字段
  client.close();
});

方式3:强制控制台显示完整嵌套结构

如果只是想查看完整的date对象内容,无需修改数据结构,可使用console.dir并设置depth: null:

collection.find({ name: "Tom" }).toArray(function(err, results) {
  if (err) return console.log(err);
  
  let res = results.map((user) => user.сategories.map((cat) => cat.products));
  console.dir(res, { depth: null }); // 强制显示所有层级的对象
  client.close();
});

注意点

  • 确保数据库中сategories是数组类型(你代码中用了map遍历),如果是单个对象,直接访问user.сategories.products即可,无需map。
  • 检查变量名拼写:你的代码中用了西里尔字母с开头的сategories,需确保和数据库字段名完全一致,避免属性找不到的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:15:50