【问题标题】:Issue while displaying fields of docs in MongoDB在 MongoDB 中显示文档字段时出现问题
【发布时间】:2020-06-17 06:27:11
【问题描述】:

我是编程新手并尽我所能,但没有任何帮助,我认为我无法找到它;) 我想按品牌显示来自 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 }

【问题讨论】:

  • 您能否在前端显示您尝试获取品牌的代码?
  • 没有前端。现在只是构建一个 api,同时从 Postman 为 /products/:categorySlug 发送 GET req 是有效的,但对于品牌来说不是,现在知道为什么
  • @HubertKopyść:我的回答解释了部分代码中缺少的内容,无论如何要检查为什么你没有获得品牌(在这里 :: if(brand)),你可以尝试打印这个@ 987654324@ & 直接在 MongoDB 中执行相同的 .findOne() 查询 & 检查是否为该输入返回任何文档?

标签: javascript mongodb express mongoose mongodb-query


【解决方案1】:

您不需要进行两次数据库调用来获取所需的数据,而是可以加入这两个集合并在一次数据库调用中获取所需的数据(尝试阅读 MongoDB 的本机$lookupMongoose.populate() - 这是对 $lookup 的一种包装)。

但是现在你可以替换这个:

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

与:

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

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

注意:不要忘记在这个文件中导入 mongoose,否则它会失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多