我是编程新手,并尽了最大努力,但在没有任何帮助的情况下,我认为我无法找到它;) 我想按品牌显示 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 $lookup
或 Mongoose 的 .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/