【发布时间】: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