node.js - 使用 nodejs 从产品的多个图像中显示图像
问题描述
我是 Node.js 的新手,正在从事一个电子商务项目,我有两种不同的product和image模型。
product.js模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
});
module.exports = mongoose.model('Product', productSchema);
image.js模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const imageSchema = new Schema({
imageUrl: {
type: String,
required: true
},
productId: {
type: Schema.Types.ObjectId,
ref: 'Product',
required: true
}
});
module.exports = mongoose.model('Image', imageSchema);
在Image.js模型中,单个产品有多个图像保存图像和产品后,我想在多个图像中显示一个产品的单个图像。这是我的控制器
exports.getProducts = (req, res, next) => {
let imagesArr = [];
Product.find({ userId: req.user._id })
.then(products => {
for (product of products){
Image.find({productId: product._id})
.then(images => {
imagesArr.push(images[0]);
})
.catch(err => {
console.log(err);
});
}
console.log("Choosed Images", imagesArr);
})
.then(result => {
return res.render('admin/products', {
pageTitle: 'Admin Product',
path: '/admin/products',
editing: editMode,
product: product,
images:imagesArr,
hasError: false,
errorMessage: null,
validationErrors: []
});
})
.catch(err => {
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
});
};
不幸的是,imageArr正在为空。我知道因为异步变得空了。请建议我如何实现这一点。 我是 Nodejs 的新手
解决方案
您可以以更简洁的方式实现这一点,而不是回调地狱。尝试以下控制器:
exports.getProducts = async (req, res, next) => {
try{
let imagesArr = [];
let products = await Product.find({ userId: req.user._id });
for (product of products){
let images = await Image.find({productId: product._id})
if(images && images.length >0) imagesArr.push(images[0]);
}
console.log("Choosed Images", imagesArr);
return res.render('admin/products', {
pageTitle: 'Admin Product',
path: '/admin/products',
editing: editMode,
product: product,
images: imagesArr,
hasError: false,
errorMessage: null,
validationErrors: []
});
}catch(err){
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
}
};
希望这对你有用。
推荐阅读
- python - 烧瓶 api 没有返回 xml
- c# - 如何异步/等待按钮单击,不仅仅是在等待页面上等待,而是在返回之前等待页面上执行的操作
- javascript - 如何在数组中的条目内搜索字符串
- java - 无法使用来自 Selenium 中的 Superclass 的 final 关键字的变量(声明的 WebElement)
- javascript - 加载函数的不同目录
- python - 在使用 str.findall 时获取 pandas 系列中的索引
- python-3.x - 有没有办法通过在其他列上找到最佳过滤器来保留最大不同值
- kframework - 什么时候对 K 个配置单元进行类型检查?
- javascript - 为什么会返回来自 javascript 选择器的值但使用 jquery 未定义
- html - HTML div 结束标记出现过早关闭错误