使用Mongoose Aggregate无法获取用户数据库中的inBagProducts数组问题求助
inBagProducts array? Looking at your code and schema setup, there are a few key issues preventing you from successfully fetching the inBagProducts array:
1. Incorrect $match Field Target
Your aggregate query uses { $match: { owner: req.userId! } }, but there’s no owner field defined in your User schema or IUser interface. Since you’re trying to fetch the logged-in user’s data, you should be matching against the user’s _id field (Mongoose automatically adds this primary key field to all documents by default).
2. Missing ObjectId Conversion for req.userId
Unlike regular Mongoose find queries, the aggregate pipeline doesn’t automatically cast string IDs to ObjectId. If req.userId is a string (common with JWT tokens or request parameters), you need to explicitly convert it to a Mongoose ObjectId to match the type of the _id field in your schema.
3. Type Definition Mismatch (Minor)
Your product type uses Pick<IUser, 'id' | 'inBagProducts'>, but Mongoose stores the primary key as _id (an ObjectId), not id (unless you’ve enabled the id virtual in your schema options). This could lead to type errors even if the query works, since the returned documents will have _id instead of id.
Corrected Query Code
Here’s the fixed version of your aggregate query addressing all these issues:
import mongoose from 'mongoose'; // Adjust type to match the actual field returned by Mongoose type Product = Pick<IUser, '_id' | 'inBagProducts'>; const products: ReadonlyArray<Product> = await UserDB.aggregate<Product>([ // Match using _id and convert req.userId to ObjectId { $match: { _id: new mongoose.Types.ObjectId(req.userId!) } }, { $sort: { createdAt: -1 } }, { $project: { inBagProducts: 1 } }, // _id is included by default ]); // Log the result to verify (access the first item since we're fetching one user) console.log('inBagProducts:', products[0]?.inBagProducts);
Additional Checks to Confirm
- Double-check that your authentication middleware correctly populates
req.userId(your current code usesreq.userId!which asserts it’s non-null, but verify it’s actually being set). - Confirm the target user document in your database has values in the
inBagProductsarray (you can check this directly in your MongoDB client like Compass). - If you don’t need the
_idfield in the result, add_id: 0to the projection:{ $project: { inBagProducts: 1, _id: 0 } }.
With these fixes, your query should now correctly retrieve the inBagProducts array for the specified user.
内容的提问来源于stack exchange,提问作者user16657995

