javascript - 在 MongoDB 中显示文档字段时出现问题

标签 javascript mongodb express mongoose mongodb-query

我是编程新手,并尽了最大努力,但在没有任何帮助的情况下,我认为我无法找到它;) 我想按品牌显示 mongoDB 的所有产品。我已经有了类别路线,但同时当我尝试对品牌实现相同的策略时,我找不到 404。 我的代码:

router.get('/:categorySlug', (req, res, next) => {

let filter = {};
if(req.query.hasOwnProperty("filter")){
    filter['price'] = req.query.price
}

const slug = req.params.categorySlug;
Category.findOne({slug: slug})
.select('_id')
.exec()
.then(category => {
    if(category){
        if(category.parent === ""){
            Product.find({category: category._id})
            .select('_id name price productPic category brand slug')
            .sort(filter)
            .exec()
            .then(products => {
                res.status(200).json({
                    message: products
                })
            })
            .catch(error => {
                return res.status(404).json({
                    message: error
                })
            })
        }
    }else{
        return res.status(404).json({
            message: 'Not Found'
        })
    }
})
.catch(er => {
    res.status(500).json({
        error: er
    });
});



router.get('/:brandSlug', (req, res, next) => {

const slug = req.params.brandSlug;
Brand.findOne({slug: slug})
.select('_id parent')
.exec()
.then(brand => {
    if(brand){
            Product.find({brand: brand._id})
            .select('_id name price productPic brand slug')
            .exec()
            .then(products => {
                res.status(200).json({
                    message: products
                })
            })
            .catch(error => {
                return res.status(404).json({
                    message: error
                })
            })
    }else{
        return res.status(404).json({
            message: 'Not Found'
        })
    }
})
.catch(er => {
    res.status(500).json({
        error: er
    });
});

类别、品牌和产品架构:

const brandSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
slug: { type: String, required: true, unique: true },


const categorySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
slug: { type: String, unique: true },


const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
slug: { type: String, required: true, unique: true },
price: { type: Number, required: true },
oldPrice: { type: Number, default: 0 },
stock: { type: Number, required: true },
description: { type: String },
productPic: [
    {
        img: String
    }
],
keyword: {type: String},
category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: true  },
brand: { type: mongoose.Schema.Types.ObjectId, ref: 'Brand', required: true }

最佳答案

您不需要执行两次数据库调用来获取所需的数据,相反,您可以连接这两个集合并在一次数据库调用中获取所需的数据(尝试阅读MongoDB的 native $lookupMongoose.populate() - 这是 $lookup 的一种包装器。

但现在你可以替换它:

Product.find({brand: brand._id})

与:

Product.find({brand: mongoose.Types.ObjectId(brand._id)})

实际问题是 brand._id 是代码中的字符串(通常当您阅读 MongoDB 中 brand 集合的文档然后记录/打印它甚至使用它时在代码中您可以看到ObjectId()被转换为字符串,因为ObjectId()来自BSON 并且不受 JSON 支持)。因此,您需要在向产品集合发出查询之前将输入 (brand._id) 从字符串转换为 ObjectId(),因为产品集合中的品牌字段的类型为 ObjectId()!!

Note : Do not forget to import mongoose in this file otherwise it would fail that given point.

关于javascript - 在 MongoDB 中显示文档字段时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60531534/

相关文章:

MongoDB 仅在某些值上查找

Java Spring Boot MongoDB 配置

node.js - Node js - 使用 Express 提供大量文件

javascript - 如何计算在 Node Js 中有多少唯一的未授权用户打开了特定的 url?

node.js - Mongoose.js - 人口和其他领域?

node.js - Node 服务器、套接字、请求和响应超时

javascript - 无法运行简单的 Jquery 函数

javascript - 表单提交成功后重定向

javascript - 如何在jquery自动完成中搜索姓名和号码?

javascript - 我应该如何使用外部样式表来设置我的单一 react 组件的样式?