实例化新对象时如何将数据推入键本身?

时间:2019-02-01 06:54:03

标签: javascript node.js express mongoose

在实现带有两个选项的符号搜索框时(DB搜索和Web Api搜索)。当我在搜索框中输入符号(例如:AAPL-大量股票)时,每次通过网络发送fetch()请求。然后将结果保存在数据库中。每次实例化new Stock()对象时,我都会将结果推送到对象数据键。原因不起作用

const stock = new Stock({ //const {Stock} = require('../models/Stock')
      symbol: curValue,// req.params.symbol
      data: webApiData.map(function (item) {
        this.data.push(item)
      })
    })

作为解决方案,推送不在new Stock({})

之外
 webApiData.map(item => {
      stock.data.push(item)
    })

以下是完整的工作代码:

(async function creatStock() {
  try {
    const webApiData = await fetchWebApi(urlCompact)
    const stock = new Stock({ //const {Stock} = require('../models/Stock')
      symbol: curValue// req.params.symbol
      // data: webApiData.map(function (item) {
      //   this.data.push(item)
      // })
    })

    webApiData.map(item => {
      stock.data.push(item)
    })

    const query = { symbol: `${curValue}` }
    const update = { $addToSet: { data: stock.data } }
    const options = { upsert: true, new: true }

    const stockResult = await Stock.findOneAndUpdate(query, update, options)
    console.log('Saved the symbol web TO db', stockResult.symbol)
    return res.send(webApiData)

  } catch (ex) {
    console.log(`creatStock error: ${ex.errors}`)
  }
})()

这是数据库的架构

const ChildSchemaData = new mongoose.Schema({
  "_id": false,
  date: { type: mongoose.Types.Decimal128 },
  open: { type: mongoose.Types.Decimal128 },
  high: { type: mongoose.Types.Decimal128 },
  low: { type: mongoose.Types.Decimal128 },
  close: { type: mongoose.Types.Decimal128 },
  volume: { type: mongoose.Types.Decimal128 }
})

const ParentSchemaSymbol = new mongoose.Schema({
  "_id": false,
  symbol: {
    type: String,
    trim: true,
    minlength: 1,
    uppercase: true,
    required: 'Please enter a valid symbol, min 1 character'
  },
  // Array of subdocuments
  data: [ChildSchemaData],
  slug: String

})

让我知道我是否想念一些东西。

0 个答案:

没有答案