简体   繁体   English

Node JS/Express 路由

[英]Node JS/Express Routing

I need a little guidance with routing in my Node/Express app.我需要一些有关 Node/Express 应用程序路由的指导。 Initially, I create a new business from the Business model (works fine).最初,我从业务模型创建了一个新业务(工作正常)。 After creating the business, I want a separate route which adds the current FX rates offered by that business (these fields will then be updated daily).创建业务后,我想要一个单独的路由,添加该业务提供的当前外汇汇率(这些字段将每天更新)。 My business model looks like this (simplified for purpose of example):我的商业模式看起来像这样(为了示例而简化):

let businessSchema = new mongoose.Schema({
   name: String,
   category: String,
   longDescription: String,
   images: [ {url: String, public_id: String} ],

   usdHkd: { type: String, default: "" },
   hkdUsd: { type: String, default: "" },
   rateCreatedAt: {
      type:Date,
      default:Date.now
   },
});

When the business is first created, only the name, category, longDesc and images are populated, with default values for the FX rate fields.首次创建业务时,仅填充名称、类别、longDesc 和图像,并使用外汇汇率字段的默认值。 That works fine using these routes:使用这些路线可以正常工作:

/* GET business new /business/new */
router.get("/new", isLoggedIn, asyncErrorHandler(businessNew));

/* POST business create /business */
router.post('/', isLoggedIn, upload.fields([{ name: 'images', maxCount: 10 }]), asyncErrorHandler(businessCreate));

I then set up separate routes/controllers like this for subsequently adding the FX rates, but I don't think these are correctly defined:然后我像这样设置单独的路由/控制器,以便随后添加外汇汇率,但我认为这些定义不正确:

/* GET business index /business */
router.get('/:id/remittance/new', asyncErrorHandler(remittanceNew));

/* GET business index /business */
router.put('/:id/remittance', asyncErrorHandler(remittanceCreate));

    //Remittances New
    async remittanceNew (req, res, next) {
        let business = await Business.findById(req.params.id);
        res.render('remittanceViews/newRemittance', { business }); 
    },

    //Business Update
    async remittanceCreate (req, res, next) {

        let business = await Business.findByIdAndUpdate(req.params.id, req.body.business);
        console.log(business);

        //update the post with any new properties
        business.usdHkd = req.body.business.usdHkd;
        business.hkdUsd = req.body.business.hkdUsd;
        business.rateCreatedAt = req.body.business.rateCreatedAt;

        //save the updated post in the db
        business.save();
        //redirect to show page
        res.redirect(`/business/${business.id}`);
    },

The error message I get when I try to update is:我尝试更新时收到的错误消息是:

Cannot read property 'usdHkd' of undefined

Can anyone please advise where I'm going wrong here?任何人都可以请告诉我哪里出错了吗? Thanks谢谢

The error message indicates that usdHkd 's parent variable in undefined .错误消息表明usdHkd的父变量在undefined 中 Most probably, this error is coming from business.usdHkd in business.usdHkd = req.body.business.usdHkd;最有可能的是,这个错误来自business.usdHkd中的business.usdHkd = req.body.business.usdHkd; (you can confirm it by adding more console.log() lines around this line and checking the outputs). (您可以通过在此行周围添加更多console.log()行并检查输出来确认它)。

If business.usdHkd = req.body.business.usdHkd;如果business.usdHkd = req.body.business.usdHkd; is giving error, that means, business is undefined .正在给出错误,这意味着business is undefined However, you don't need this line as business is already updated by findByIdAndUpdate .但是,因为你并不需要这一行business已经被更新findByIdAndUpdate

READ: Model.findByIdAndUpdate() and Promises in Mongoose阅读: Mongoose 中的Model.findByIdAndUpdate()Promises

//Business Update
async remittanceCreate (req, res, next) {

    let business = await Business.findByIdAndUpdate(req.params.id, req.body.business);
    console.log(business);

    // Below code is not required since findByIdAndUpdate() will update your model
    /*
    //update the post with any new properties
    business.usdHkd = req.body.business.usdHkd;
    business.hkdUsd = req.body.business.hkdUsd;
    business.rateCreatedAt = req.body.business.rateCreatedAt;

    //save the updated post in the db
    business.save();
    */

    //redirect to show page
    res.redirect(`/business/${business.id}`);
},

UPDATE更新

You told that business is defined, but it's not getting updated.你告诉过business已经定义,但它没有得到更新。 The reason is findOneAndUpdate() requires new option to be set as true else findOneAndUpdate() returns the old object (before updating it -- in a sense).原因是findOneAndUpdate()需要将new选项设置为true否则findOneAndUpdate()返回旧对象(在更新之前 - 从某种意义上说)。 So, please change the first line of remittanceCreate() to:因此,请将remittanceCreate()的第一行更改为:

let business = await Business.findByIdAndUpdate(req.params.id, req.body.business, {new: true});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM