【问题标题】:Cannot read property 'metadata' of null Nodejs无法读取 null Nodejs 的属性“元数据”
【发布时间】:2019-02-21 05:39:40
【问题描述】:

这是我的错误:

 TypeError: Cannot read property 'metadata' of null
 at gfs.files.findOne (M:\FinalProject\Commerce\routes\index.js:187:13)
 at result (M:\FinalProject\Commerce\node_modules\mongodb\lib\utils.js:414:17)

这是我的代码:

    router.get('/:filename', (req,res) => {
    const img = req.params.filename; // Filename
     gfs.files.findOne({filename: img}, (req,file) =>{


  if(file.metadata.brand=="Mango"){
  const brand = "Mango";
   displayOne(brand);
  }
  else if(file.metadata.brand=="Cocotail")
  {
  const brand = "Cocotail";
   displayOne(brand);
  }
  else if(file.metadata.brand==null)
  {  
   console.log("Null");

   }




   function displayOne(brand)
    {
   gfs.files.find({'metadata.brand': brand }).toArray((err,files)=>{

   if(!file || file.length ===0)
   {
   return res.status(404).json({
    err: 'No files exist'
   });
  }

   if(file.contentType === 'image/jpeg' || file.contentType === 'image/png')
  {

   file.isImage = true;
   }
   else
  {
  res.status(404).json({
    err: 'Not an image'
  });
  file.isImage = false;
  }


   res.render('singleproduct',{
    file:file,
    relatedProduct:files, // Related Products
    isSearch:0

  });
  });

  }

 });
 });

请给我有关此错误的任何想法。我无法找出此错误的主要原因是什么。我在谷歌上搜索过,但没有合适的解决方案。______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

谢谢

【问题讨论】:

  • 第 187 行是哪一行?直接的问题可能是file.metadata 中的file 为空,这意味着(我认为)findOne() 没有找到...
  • if(file.metadata.brand=="Mango"){
  • 你能推荐我如何在用户点击产品时显示相关产品吗?这段代码主要是为了获取相关的商品项目
  • 这意味着filenull。当变量file 被填充时,错误发生在此行之前的某处。

标签: node.js mongodb ejs


【解决方案1】:

你有没有安慰上面得到的东西

(file.metadata.brand=="Mango")

在文件中?似乎您没有从

获得任何数据

gfs.files.findOne({filename: img}

试试这个:

 if(file && file.metadata.brand=="Mango"){
  const brand = "Mango";
   displayOne(brand);
  }
  else if(file && file.metadata.brand=="Cocotail")
  {
  const brand = "Cocotail";
   displayOne(brand);
  }
  else if(file && file.metadata.brand==null)
  {  
   console.log("Null");

   }
else{
    console.log("didinot find value")
}

【讨论】:

  • 我得到了结果 const img = req.params.filename; -> 这里我得到图像文件名 gfs.files.findOne({filename: img}, (req,file) =>{ -> 我使用 img 搜索了数据库
  • gfs.files.findOne({filename: img}) 这是您从收藏中获取数据的部分吗?您没有从 db 获取变量文件中的数据。
  • 不!我从集合中得到了数据。问题是当我渲染另一个页面时,它会显示我上面显示的错误。我不明白为什么这个错误会显示在另一个渲染上。
  • 看到错误说“空元数据”并且元数据在对象“文件”中。你能分享你从 db 获得的数据吗?
  • 你能看看我最新的问题吗?
猜你喜欢
  • 2019-06-22
  • 1970-01-01
  • 2020-06-12
  • 2016-05-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多