如何从api获取数据并将其存储在mongodb模式数组中?

时间:2019-06-15 06:55:55

标签: javascript node.js mongodb api referenceerror

我正在尝试在nodejs中查询一个api,并将在主体中获取的数据存储到一个数组中,然后将该数组推入mongodb模式,但是我遇到了麻烦。我被抛出一个未处理的promiserejecteion警告错误。

我已经尝试过了。

//@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");
    }
  }
);

猫鼬模式:

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
  }
});

显示的错误:

UnhandledPromiseRejectionWarning:ReferenceError:价格未定义     在router.post(C:\ Users \ Saksham \ Projects \ Invenst \ routes \ api \ portfolio.js:62:9)     在Layer.handle [作为handle_request](C:\ Users \ Saksham \ Projects \ Invenst \ node_modules \ express \ lib \ router \ layer.js:95:5)     在下一个(C:\ Users \ Saksham \ Projects \ Invenst \ node_modules \ express \ lib \ router \ route.js:137:13)     出现错误时(C:\ Users \ Saksham \ Projects \ Invenst \ node_modules \ express-validator \ check \ check.js:16:7)     在process._tickCallback(内部/进程/next_tick.js:68:7) (节点:7680)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。引发此错误的原因可能是抛出了一个没有catch块的异步函数,或者是拒绝了一个.catch()无法处理的承诺。 (拒绝ID:2) (节点:7680)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。

1 个答案:

答案 0 :(得分:0)

Node抱怨代码中未声明的变量。未声明的变量都在您的 newStock 对象中。要实例化一个新的猫鼬模式,您需要调用const newStock = new PortfolioSchema({...})

那么您根本就不会在数据库中插入文档;有了新对象后,请尝试通过插入方法传递它:Portfolio.insert(newStock)

请查看this