求助: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
相关产品推荐
相关产品推荐

