tpick tpick - 17 days ago 6
Node.js Question

Result from mongoose query unavailable in parent scope

I'm new to javascript and node and am having trouble returning the result from a mongoose query to an object I can work with. My app currently parses the body of a post request into cache, uses a field in the cached object (mlcRecord.existFixture) to query the database, and returns an object from which to grab additional properties. This part of the code works fine. However, the additional properties are undefined outside of the .then scope.

I'm sure I'm missing something basic so any guidance folks can provide is appreciated.

router.route('/mlc')
.post(function (req,res){
var mlcRecord = new mlcInputObj(req.body);
async.series([
function (callback) {
function setWattages(mlcRecord) {

// load the existFixture TechnologyID
ltgTechnologies.findOne({TechnologyID: mlcRecord.existFixture}).exec()

// capture the technologyID
.then(function(ltgTechnology){
mlcRecord.existFixtureWatts = ltgTechnology.SystemWatts;
return mlcRecord;
});
}

setWattages(mlcRecord);

console.log('mlcRecord: ', mlcRecord); // existFixtureWatts displays as undefined
callback();
}
], function (err) {
res.json(mlcRecord);
});
});

Answer

Your code is overcomplicated.

async.series not suitable for Your purpose.

Here is fix:

router
  .route('/mlc')
  .post(function (req,res){
    var mlcRecord = new mlcInputObj(req.body);

    // load the existFixture TechnologyID
    ltgTechnologies
      .findOne({TechnologyID: mlcRecord.existFixture})
      .exec(function(err, result) {
        mlcRecord.existFixtureWatts = null;
        if(result) {
          mlcRecord.existFixtureWatts = result.SystemWatts;
        }
        res.send(mlcRecord);
      });
  });

but if You want to save mlcRecord to database:

router
  .route('/mlc')
  .post(function (req,res){

    var mlcRecord = new mlcInputObj(req.body); // creating mlcRecord instance

    mlcRecord.save(function(err) { // inserting to database
      if(err) return res.status(500).send({err});

      // adding to mlcRecord  existFixtureWatts
      ltgTechnologies
        .findOne({TechnologyID: mlcRecord.existFixture})
        .exec(function(err, result) {
          mlcRecord.existFixtureWatts = null;
          if(result) {
            mlcRecord.existFixtureWatts = result.SystemWatts;
          }
          res.send(mlcRecord);
        });
    });

  });
Comments