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

使用Mongoose的find()获取商品Schema中所有订单返回null的问题

问题原因

Products.find({}) 返回的是产品文档的数组,而非单个产品对象。数组本身不存在 orders 属性,所以 result.orders 会返回 null/undefined;而 findById() 返回的是单个产品文档,因此能正常访问其 orders 属性。

解决方案

方案1:提取所有产品的订单并合并

修改控制器返回逻辑,遍历查询结果,将每个产品的 orders 提取后合并为一个数组:

module.exports.getAllOrders = async (request, response) => {
    const decoded = await auth.decode(request.headers.authorization);
    if(decoded.isAdmin){
        try {
            const products = await Products.find({});
            // 提取所有订单并合并成一维数组
            const allOrders = products.flatMap(product => product.orders);
            response.send(allOrders);
        } catch(error) {
            console.log(error);
            response.status(500).send(error);
        }
    } else {
        return response.status(401).send("User must be ADMIN to access this functionality");
    }
}

方案2:用MongoDB聚合管道直接查询订单

如果仅需订单数据,无需产品其他信息,用聚合管道能更高效地提取:

module.exports.getAllOrders = async (request, response) => {
    const decoded = await auth.decode(request.headers.authorization);
    if(decoded.isAdmin){
        try {
            const allOrders = await Products.aggregate([
                // 展开每个产品的orders数组
                { $unwind: "$orders" },
                // 将orders字段作为根文档返回
                { $replaceRoot: { newRoot: "$orders" } }
            ]);
            response.send(allOrders);
        } catch(error) {
            console.log(error);
            response.status(500).send(error);
        }
    } else {
        return response.status(401).send("User must be ADMIN to access this functionality");
    }
}

额外优化建议

  • 避免 async/await 和 .then()/.catch() 混用,统一用 try/catch 处理异步错误,代码逻辑更清晰
  • 变量名修正:hassedPassword 改为 decoded 更贴合语义(实际是解码后的token,而非哈希密码)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 14:53:05