0
votes

I am trying to query an api in nodejs and store the data obtained in the body to an array and then push that array to a mongodb schema but I am having trouble with that. I am getting thrown an unhandledpromiserejecteion warning error.

I have tried this.

//@route POST api/portfolio/stock
//@desc post new stock to the portfolio.
//@access private
router.post(
  "/stock",
  auth,
  [
    check("symbol", "symbol is require or incorrect.")
      .not()
      .isEmpty(),
    check("qty", "Quantity of the stock purchased is required")
      .not()
      .isEmpty()
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if(!errors.isEmpty) {
        return res.status(400).json({ errors: errors.array() });
    }

    const {
        stock,
        qty
    } = req.body

    const newStock = {
        stock,
        qty,
        price,
        lastclose,
        change,
        open,
        high,
        low,
        volume,
        changepercent
    }

    try {
        const portfolio = await Portfolio.findOne({ user: req.user.id });

        const options = {
            uri: `https://https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${stock}&apikey=${config.get('API_KEY')}`,
            method: 'GET',
            headers: { 'user-agent': 'node.js' }
        }; 

        request(options, (error, response, body) => {
            if(error) console.error(error);

            if(response.statusCode !== 200){
                res.status(404).json({msg: 'No stock for this symbol found. '});
            }

            const content = JSON.parse(body);
            const quote = content['Global Quote'];
            newStock.price = quote['05. price'];
            newStock.lastclose = quote['08. previous close'];
            newStock.change = quote['09. change'];
            newStock.open = quote['02. open'];
            newStock.high = quote['03. high'];
            newStock.low = quote['04. low'];
            newStock.volume = quote['06. volume'];
            newStock.changepercent = quote['10. change percent'];



        });

        portfolio.stocks.unshift(newStock);

        await portfolio.save();

        res.json(portfolio);


    } catch (err) {
      console.error(err.message);
      res.status(500).send("Server Error");
    }
  }
);

Mongoose Schema:

const PortfolioSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user"
  },
  stocks: [
    {
      stock: {
        type: String,
        required: true
      },
      qty: {
        type: String,
        required: true
      },
      price: {
        type: String
      },
      lastclose: {
        type: String
      },
      change: {
        type: String
      },
      open: {
        type: String
      },
      high: {
        type: String
      },
      low: {
        type: String
      },
      volume: {
        type: String
      },
      changepercent: {
        type: String
      }
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }
});

The error showing up:

UnhandledPromiseRejectionWarning: ReferenceError: price is not defined at router.post (C:\Users\Saksham\Projects\Invenst\routes\api\portfolio.js:62:9) at Layer.handle [as handle_request] (C:\Users\Saksham\Projects\Invenst\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\Saksham\Projects\Invenst\node_modules\express\lib\router\route.js:137:13) at runner.then.errors (C:\Users\Saksham\Projects\Invenst\node_modules\express-validator\check\check.js:16:7) at process._tickCallback (internal/process/next_tick.js:68:7) (node:7680) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2) (node:7680) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1

1 Answers

0
votes

Node complains about undeclared variables in your code. The undeclared variables are all in your newStock object. To instantiate a new mongoose Schema you need to call const newStock = new PortfolioSchema({...}).

Then you are not inserting the document in the database at all; once you have your new object, try to pass it in the insert method: Portfolio.insert(newStock)

Please take a look at this.