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

求助:MongoDB与Mongoose中toArray is not a function错误排查

问题解决:Mongoose聚合查询报错“toArray is not a function”及返回undefined

核心原因

Mongoose的aggregate()方法返回的是Aggregate实例对象,并非MongoDB原生驱动的游标,因此不存在toArray()方法。同时你的代码存在语法和逻辑错误,这也是移除toArray()后返回undefined的原因。

修复步骤

  • 替换执行方法:Mongoose聚合查询需用exec()方法执行并返回Promise,无需toArray()
  • 修正变量名:JavaScript变量名不能含空格,将cart Items改为cartItems、user Id改为userId
  • 修正$lookup参数:from需填写集合名称(如products),而非db.products
  • 修正resolve参数:resolve应直接传入变量cartItems,而非模板字符串

修复后的完整代码

getCartProducts: (userId) => {
    return new Promise(async (resolve, reject) => {
        try {
            let cartItems = await db.cart.aggregate([
                {
                    $match: { user: userId }
                },
                {
                    $lookup: {
                        from: "products",
                        let: { proList: '$products' },
                        pipeline: [
                            {
                                $match: {
                                    $expr: {
                                        $in: ["$_id", '$$proList']
                                    }
                                }
                            }
                        ],
                        as: 'cartItems'
                    }
                }
            ]).exec();
            resolve(cartItems);
        } catch (err) {
            reject(err);
        }
    });
}

额外优化

由于aggregate().exec()本身返回Promise,可省略手动包裹的Promise,简化代码:

getCartProducts: async (userId) => {
    return db.cart.aggregate([
        { $match: { user: userId } },
        {
            $lookup: {
                from: "products",
                let: { proList: '$products' },
                pipeline: [
                    { $match: { $expr: { $in: ["$_id", '$$proList'] } } }
                ],
                as: 'cartItems'
            }
        }
    ]).exec();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:01:04