【问题标题】:MongoDB field returns a number but makes javascript variable undefined [duplicate]MongoDB字段返回一个数字,但使javascript变量未定义[重复]
【发布时间】:2019-05-10 03:04:09
【问题描述】:

价值

found.totalfunds = 99

但是当我将它分配给变量时

资金

它在 console.log(funds) 上返回 undefined

 router.get("/:id/managefunds/",middleware.isLoggedIn,function(req,res){

    console.log("Manage Funds");
     var societyId = req.params.id;
     // res.send(societyId);
     var funds ;
     Society.findById({_id:societyId},function(err,found){
        console.log("fromMongo"+found.totalFunds);
        funds = found.TotalFunds;
     });
     console.log("FUNDSSSS: "  + funds);

     res.render("campgrounds/managefunds",{parm:societyId,funds});

});

console.log("fromMongo"+found.totalFunds); 这会返回一个我默认设置的数字。

【问题讨论】:

  • 当您打印资金时,它仍然是未定义的。在回调函数中打印它。
  • 我想在查询中赋值,然后在外面做计算。
  • 我认为只是一个拼写错误funds = found.TotalFunds,不应该被find.totalFunds
  • 在我的模型中是 totalFunds
  • @KrishnaSingh 我也发现了,但在资金的情况下它仍然输出未定义,但在 found.totalFunds 上输出“369”(正确输出)

标签: node.js mongodb express mean-stack


【解决方案1】:

Society.findById 有一个回调,因为它是异步

您必须修改代码以仅在执行回调时继续:

router.get("/:id/managefunds/",middleware.isLoggedIn,function(req,res){

    console.log("Manage Funds");
     var societyId = req.params.id;
     // res.send(societyId);
     var funds ;
     Society.findById({_id:societyId},function(err,found){
        console.log("fromMongo"+found.totalFunds);

        funds = found.TotalFunds;     console.log("FUNDSSSS: "  + funds);

        res.render("campgrounds/managefunds",{parm:societyId,funds});
     });
});

【讨论】:

  • 有效!谢谢!
猜你喜欢
  • 2014-12-05
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 2020-08-14
  • 2019-05-03
  • 2013-06-26
相关资源
最近更新 更多