【发布时间】:2021-09-22 04:09:23
【问题描述】:
我是后端和数据库的新手。如何从 MongoDB 获取数据并将其显示在市场上?
我刚刚为产品信息创建了一个 MongoDB 集群,并希望在我的市场上显示产品信息。我希望从我的 MongoDB 集群中检索数据(图像和文本),并为每个产品卡显示不同的产品信息和图像。
这是我当前的市场产品卡代码。您能告诉我如何添加后端代码以将前端连接到数据库,并为每个产品卡显示不同的产品图像和信息吗?
function Example(product)
{
console.log (product)
product.map (product=>{return product.imagelink})
var items = [
{
src: product.product.media,
}
]
return (
<Carousel
width= '95%'
>
{
items.map( (item, i) => <Item key={i} item={item} /> )
}
</Carousel>
)
}
function Item(props)
{
return (
<Link to={{
pathname: '/app/print',
state: { id: 123 },
}}
>
<Paper
square= "true"
width= '100%'
elevation= {0}
>
<h2>{props.item.name}</h2>
<p>{props.item.description}</p>
<img src={props.item.link}></img>
{/* <Button className="CheckButton">
Check it out!
</Button> */}
</Paper>
</Link>
)
}
const ProductCard = ({ product, ...rest }) => (
<Card
sx={{
display: 'flex',
flexDirection: 'column',
height: '100%'
}}
{...rest}
>
<CardContent>
<Box
sx={{
display: 'flex',
justifyContent: 'center',
pb: 3
}}
>
<Example
product= {product}
/>
{/* <Avatar
alt="Product"
src={product.imageLink[0]}
variant="square"
/> */}
</Box>
<Typography
align="center"
color="textPrimary"
gutterBottom
variant="h4"
>
{product.title}
</Typography>
<Typography
align="center"
color="textPrimary"
variant="body1"
>
{product.description}
</Typography>
</CardContent>
<Box sx={{ flexGrow: 1 }} />
<Divider />
<a></a>
<Box sx={{ p: 2 }}>
<Grid
container
spacing={2}
sx={{ justifyContent: 'space-between' }}
>
<Grid
item
sx={{
alignItems: 'center',
display: 'flex'
}}
>
{/* <AccessTimeIcon color="action" /> */}
<Typography
color="textSecondary"
display="inline"
sx={{ pl: 1 }}
variant="body2"
>
Updated on {moment(product.dateUpdated).format('llll')}
Price: 20,000USD
</Typography>
</Grid>
<Grid
item
sx={{
alignItems: 'center',
display: 'flex'
}}
>
<Button className="CheckButton">
<AddShoppingCartIcon color="action" />
</Button>
<Typography
color="textSecondary"
display="inline"
sx={{ pl: 1 }}
variant="body2"
>
{product.price}
</Typography>
</Grid>
</Grid>
</Box>
</Card>
);
ProductCard.propTypes = {
product: PropTypes.object.isRequired
};
export default ProductCard;
在代码中,我目前使用的是固定在前端的虚拟数据。您能否告诉我如何从我的 MongoDB 集群中检索数据(图像和文本)并为每个产品卡显示不同的产品信息和图像
【问题讨论】:
标签: javascript node.js database mongodb