面对在Nodejs项目中编辑产品时遇到的问题

时间:2019-06-21 17:27:46

标签: javascript node.js express

嘿,我是Nodejs的新手,我正在尝试通过Express项目在Nodejs中编辑产品

因此,更新存储在products.json文件中的产品时,我在这里面临的问题

控制器文件

const Product = require('../models/product');
exports.posteditproduct = (req, res, next) => {
    const upprodid = req.body.productid
    const upprodtitle = req.body.title
    const upprodprice = req.body.price
    const upprodimg = req.body.imageurl
    const upproddesc = req.body.description
    const updatedproduct = new Product(upprodid, upprodtitle, upprodimg, upprodprice, upproddesc);
    updatedproduct.save()
    res.redirect('/')
}

产品型号

const fs=require('fs');
const path=require('path');
module.exports=class Product{
constructor(id,title,imageurl,price,description){
    this.id=id
    this.title=title;
    this.imageurl=imageurl
    this.price=price
    this.description=description
}

save(){
  if(this.id){
  console.log(this.id)   //prints the id correctly

  const p=path.join(path.dirname(process.mainModule.filename),
'data','products.json')
  fs.readFile(p,(err,data)=>{
    const datainfile=JSON.parse(data)
    const existproduct=datainfile.findIndex
(prod=>prod.id===this.id)

        const upproduct=[...datainfile]
        console.log('spread=================================')

         console.log(this)
        upproduct[existproduct]=this
        fs.writeFile(p,JSON.stringify(upproduct),err=>{
            console.log(upproduct) //prints all the data that i have in my file and replaces the updated product with the old product, the output is what i expected..
        })

    })


  }
  else 
  this.id=Math.random().toString()
    const p=path.join(path.dirname(process.mainModule.filename),
  'data','products.json')

    fs.readFile(p,(err,data)=>{
        let products
        if(err){
           products=[] 
        }
        if(!err){
            products=JSON.parse(data)
        }
        products.push(this)
        fs.writeFile(p,JSON.stringify(products),err=>{
            // console.log(err)
        })
    })
    }


    }

更新前的输出

[
    Product {
        id: '0.3812592138104218',
        title: 'Burger',
        imageurl:
            'https://www.seriouseats.com/recipes/images/2015/07/20150702-sous- vide - hamburger - anova - primary - 1500x1125.jpg',
        price: '7.5',
        description: 'Very tasty, must try !'
    },
    {
        title: 'Pepsi',
        imageurl: 'https://target.scene7.com/is/image/Target/GUEST_26aa6df7-2fdf - 4b4b- 9f3b - d2ea31b5d685 ? wid = 488 & hei=488 & fmt=pjpeg',
        price: '5',
        description: 'Strong !',
        id: '0.9829663341239048'
    }
]

更新后的输出(更新Burger产品的标题)

[
    Product {
        id: '0.3812592138104218',
        title: 'Burger after trying to update',
        imageurl: 'https://www.seriouseats.com/recipes/images/2015/07/20150702-sous-vide-hamburger-anova-primary-1500x1125.jpg',
        price: '7.5',
        description: 'Very tasty, must try !'
    },
    {
        title: 'Pepsi',
        imageurl: 'https://target.scene7.com/is/image/Target/GUEST_26aa6df7-2fdf-4b4b-9f3b-d2ea31b5d685?wid=488&hei=488&fmt=pjpeg',
        price: '5',
        description: 'Strong !',
        id: '0.9829663341239048'
    }
]

一切都很好...现在终于在我的保存方法中,我将数据写入文件中,因此出现了问题...当我将所有数据写入文件中时,更新的产品不会替代旧产品其中它也被添加到我的json文件中,但是我想用新的条目替换旧的条目,而不是将其添加到旧的条目中

1 个答案:

答案 0 :(得分:1)

这就是为什么您应该indent您的代码。您忘记在else之后加上花括号了,

else
   this.id = Math.random().toString()
const p = path.join(path.dirname(process.mainModule.filename), 'data', 'products.json')
...

这意味着,即使存在产品,else块之后没有this.id = ...的代码也会运行。因为它没有大括号包围。

所以这样做:

else{
    this.id = Math.random().toString()
    const p = path.join(...)
    fs.readFile(p, (err, data) => { 
        ...
        })
    })
}

现在,从Node v0.5.x开始,还可以要求JSON文件,

const product = require(path.join(..., 'product.json'));