所以我正在为电子商务平台构建搜索功能。我决定写类方法 that search for a query match in the category model以及。{ product model。这就是我所表达的route looks like 。当我运行并尝试在此配置中搜索时,我得到500错误。
with this stack trace。当我评论类别 look up like so时,会出现奇怪的现象。然后搜索功能工作得很好,但它只从产品模型中获取数据。如果我注释掉产品型号,则类别类方法仍然无效。我试过console.logging class.search方法的结果,我得到undefined。我的预感是热切的加载不能以某种方式工作......
路线
const router = require('express').Router()
const { Category, Product } = require('../db/models')
const checkAccess = require('./checkAccess')
const Sequelize = require('sequelize')
module.exports = router
router.get('/', async (req, res, next) => {
try {
const productResult = await Product.search(req.query.search)
const categoryResult = [] //await Category.search(req.query.search)
if (![...productResult, ...categoryResult].length) {
res.json([])
} else if (productResult.length && categoryResult.length) {
const foundProducts = [...productResult, ...categoryResult[0].products]
const foundProductsNoDuplicates = []
const setOfUniqueIds = new Set()
foundProducts.forEach(product => {
if (!setOfUniqueIds.has(product.id)) {
setOfUniqueIds.add(product.id)
foundProductsNoDuplicates.push(product)
}
})
res.json(foundProductsNoDuplicates)
} else if (productResult.length) {
res.json([...productResult])
} else {
res.json([...categoryResult[0].products])
}
} catch (err) {
next(err)
}
})
模特
'use strict'
const Sequelize = require('sequelize')
const db = require('../db')
const Category = require('./category')
const Product = db.define('product', {
name: {
type: Sequelize.STRING,
allowNull: false
},
inventory: {
type: Sequelize.INTEGER,
defaultValue: 0
},
price: {
type: Sequelize.DECIMAL(10, 2),
allowNull: false
},
imgUrl: {
type: Sequelize.STRING,
defaultValue: '../../images/default-product.jpg'
},
description: {
type: Sequelize.TEXT,
allowNull: false
},
status: {
type: Sequelize.ENUM('inStock', 'outOfStock', 'unavailable')
}
}, {
hooks: {
beforeCreate: product => {
if (product.imgUrl === '') {
product.imgUrl = '../../images/default-product.jpg'
}
}
}
})
Product.search = async function (query) {
const result = await this.findAll({
where: {
name: {
[Sequelize.Op.iLike]: '%' + query + '%'
},
status: 'inStock',
},
include: [{ model: Category }]
})
return result
}
module.exports = Product
'use strict'
const Sequelize = require('sequelize')
const db = require('../db')
const Product = require('./product')
const Category = db.define('category', {
name: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.TEXT,
allowNull: false
}
})
Category.search = function (query) {
return this.findAll({
where: {
name: {
[Sequelize.Op.iLike]: '%' + query + '%'
},
},
include: [Product],
})
}
module.exports = Category