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

Mongoose返回文档对象后无法获取history数组,求解决方案

解决Mongoose返回Document无法直接访问history数组的问题

首先注意你的代码存在语法错误:findOneAndUpdate的第二个参数必须是一个对象,你写的$push: {'history': historyData }缺少外层大括号,正确写法是{$push: {'history': historyData }},这个错误先修正。

接下来是核心问题:Mongoose默认返回的是Document实例,不是普通JavaScript对象。控制台打印时会展开显示所有属性,但直接通过.访问或解构时,因为Document的属性访问依赖内部的getter机制,可能出现返回undefined的情况。

给你两种可行的解决方法:

方法一:使用lean()选项返回普通JS对象

在查询选项里添加lean: true,这样Mongoose会直接返回数据库的原始JSON对象,而非Document实例,就能直接访问history数组:

ProductHistory.findOneAndUpdate(
    {productId: product._id},
    {$push: {'history': historyData }},
    {upsert: true, new: true, lean: true}
).exec((err, success) => {
    if (err){
         console.log('Error: ', err)        
    }
    console.log('success is: ', success)
    // 现在可以正常遍历history数组
    success.history.forEach(item => {
        // 你的处理逻辑
    })
})

方法二:将Document转换为普通对象

如果不想使用lean(),可以调用Document实例的toObject()或toJSON()方法,把它转换成普通JS对象后再访问属性:

ProductHistory.findOneAndUpdate(
    {productId: product._id},
    {$push: {'history': historyData }},
    {upsert: true, new: true}
).exec((err, success) => {
    if (err){
         console.log('Error: ', err)        
    }
    const plainObj = success.toObject();
    console.log('plainObj.history: ', plainObj.history);
    // 正常遍历
    plainObj.history.forEach(item => {
        // 你的处理逻辑
    })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:20:31