首页 > 解决方案 > 使用 nodejs 从产品的多个图像中显示图像

问题描述

我是 Node.js 的新手,正在从事一个电子商务项目,我有两种不同的productimage模型。

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 的新手

标签: node.jsmongoose

解决方案


您可以以更简洁的方式实现这一点,而不是回调地狱。尝试以下控制器:

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);
  }
};

希望这对你有用。


推荐阅读