使用nodejs从数据库中获取特定数据
Take specific data from database with nodejs
你好,我有一些路线,我正在从数据库接收数据
router.get('/', expressAsyncHandler(async (req,res) => {
const products = await Product.find({})
res.json(products)
}))
通过这条路线,我得到了 mongoDB
的所有产品
我想获得同一类别的所有产品,所以我开始尝试新路线
router.get('/roundBall', expressAsyncHandler(async (req,res) => {
const products = await Product.find({})
const roundball= products._category == 'Rounded'
res.json(products)
}))
但它不起作用,在我的本地主机上,我在屏幕上显示错误。谁能帮我解决这个问题?
products._category == 'Rounded' 是一个比较,所以它总是 return true of false。您需要做的是映射元素并将每个元素的类别与 'Rounded'.
进行比较
目前,正在从 mongoDB 检索所有产品。那么 node.js 中按类别过滤的尝试是不正确的。
解决此问题的一种方法是更正 node.js 端的过滤方式:
roundball
应该使用 Array.filter
创建,这样。
const roundball= products.filter( product => product._category === 'Rounded')
但是,只查询 mongoDB 对应于所需类别的产品会更有效:
const roundball = await Product.find({_category: 'Rounded'})
这样,mongodb 和 node.js 之间需要传输的数据就更少了。
你好,我有一些路线,我正在从数据库接收数据
router.get('/', expressAsyncHandler(async (req,res) => {
const products = await Product.find({})
res.json(products)
}))
通过这条路线,我得到了 mongoDB
的所有产品我想获得同一类别的所有产品,所以我开始尝试新路线
router.get('/roundBall', expressAsyncHandler(async (req,res) => {
const products = await Product.find({})
const roundball= products._category == 'Rounded'
res.json(products)
}))
但它不起作用,在我的本地主机上,我在屏幕上显示错误。谁能帮我解决这个问题?
products._category == 'Rounded' 是一个比较,所以它总是 return true of false。您需要做的是映射元素并将每个元素的类别与 'Rounded'.
进行比较目前,正在从 mongoDB 检索所有产品。那么 node.js 中按类别过滤的尝试是不正确的。
解决此问题的一种方法是更正 node.js 端的过滤方式:
roundball
应该使用 Array.filter
创建,这样。
const roundball= products.filter( product => product._category === 'Rounded')
但是,只查询 mongoDB 对应于所需类别的产品会更有效:
const roundball = await Product.find({_category: 'Rounded'})
这样,mongodb 和 node.js 之间需要传输的数据就更少了。