【问题标题】:How to push data to a mongoose array in collection?如何将数据推送到集合中的猫鼬数组?
【发布时间】:2019-05-15 20:33:44
【问题描述】:

我正在创建一个 CronJob,以每隔 00:01 更新我的 currencies 集合中的每个 key。这是我的currencies 集合架构:

const CurrencySchema = new mongoose.Schema({
    currency: {
        type: String,
        unique: true,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    exchange_rate: {
        type: SchemaTypes.Double,
        required: true
    },
    spread: {
        type: SchemaTypes.Double,
        required: true,
        default: 0,
        select: false
    },
    lastUpdate: {
        type: Date
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    history: [{
        date: Date,
        rate: SchemaTypes.Double
    }]
});

我尝试像这样创建一个 CronJob:

const CronJob = require("cron").CronJob;
const currencies = require("../../models/currencies");

module.exports = new CronJob("* 1 0 * * *", async function() {
    await currencies.find({}).map(currency => currency.history.push({
        date: Date.now(),
        rate: currency.exchange_rate
        })
    )
});

所以,对于每一个currency,我想将push 加入history 数组中的Date.now()exchange_rate 那个时刻的货币。

问题是我得到了这个异常:

UnhandledPromiseRejectionWarning:TypeError:无法读取属性 未定义的“推”

我应该如何解决它?

谢谢!

编辑:地图函数内的console.log(currency) 显示如下:

[
  {
    _id: 5cbdefd4f5bcec257fcec791,
    currency: 'VES',
    exchange_rate: 5321.709437805213,
    createdAt: 2019-04-22T16:46:12.350Z,
    __v: 0,
    lastUpdate: 2019-05-15T20:40:08.649Z,
    name: 'Venezuelan Bolivar',
    history: []
  },
  {
    _id: 5cbdf078f5bcec257fcec792,
    currency: 'BTC',
    exchange_rate: 7290,
    createdAt: 2019-04-22T16:48:56.182Z,
    __v: 0,
    lastUpdate: 2019-05-15T20:41:01.122Z,
    history: []
  },
  {
    _id: 5cbe1ebccd6e6a2b4738070d,
    currency: 'BRL',
    exchange_rate: 4.2382007085048015,
    createdAt: 2019-04-22T20:06:20.796Z,
    __v: 0,
    lastUpdate: 2019-05-15T20:41:02.817Z,
    name: 'Brazilian Real',
    history: []
  },
  {
    _id: 5cbe1ec8cd6e6a2b4738070e,
    currency: 'INR',
    exchange_rate: 78.43526089163238,
    createdAt: 2019-04-22T20:06:32.322Z,
    __v: 0,
    lastUpdate: 2019-05-15T20:41:02.814Z,
    name: 'Indian Rupee',
    history: []
  },
  {
    _id: 5cbe1ecfcd6e6a2b4738070f,
    currency: 'ZAR',
    exchange_rate: 15.984316920438957,
    createdAt: 2019-04-22T20:06:39.513Z,
    __v: 0,
    lastUpdate: 2019-05-15T20:41:03.135Z,
    name: 'South African Rand',
    history: []
  },
  {
    _id: 5cbe1ed9cd6e6a2b47380710,
    currency: 'ARS',
    exchange_rate: 50.264175514403284,
    createdAt: 2019-04-22T20:06:49.520Z,
    __v: 0,
    lastUpdate: 2019-05-15T20:41:04.134Z,
    name: 'Argentinian Peso',
    history: []
  }
]

所以我假设正在创建另一个数组,而不是返回每个单独的对象

【问题讨论】:

  • 货币对象在地图函数中是什么样子的?
  • 从您的货币模型中获取history 数组时出了点问题,因为那是未定义的。您能与我们分享货币数据吗?
  • console.log(currency) in map 函数给出了一个包含每个键对象的数组
  • 您需要在您的问题中添加此类细节,作为编辑 - 请显示您的模型的内容。您目前没有向我们提供足够的细节来处理您的问题。
  • 当然,抱歉。立即行动

标签: javascript node.js mongoose


【解决方案1】:

根据Mongoose Update API,正确的语法应该是:

await currencies.find({}).map(currency => currencies.update({ "_id": currency._id},
  { "$push": { "history": { date: Date.now(), rate: currency.exchange_rate } } },
  function (err, raw) {
    if (err) return handleError(err);
    console.log('The raw response from Mongo was ', raw);
  }
));

根据新信息进行更新。可能需要显式返回 Mongoose 调用,并且肯定可以重构:

await currencies.find({}).map(currencyList => { 
  currencyList.forEach(currency =>  {
    currencies.updateMany({ "_id": currency._id},
      { "$push": { "history": { date: Date.now(), rate: currency.exchange_rate } } },
      function (err, raw) {
        if (err) return handleError(err);
        console.log('The raw response from Mongo was ', raw);
      }
    )
  })
});

【讨论】:

  • 这会返回一个UnhandledPromiseRejectionWarning: TypeError: currency.update is not a function
  • 尝试将currency.update 替换为CurrencySchema.update。您可能需要明确导出 CurrencySchema 或以不同方式将其导入您正在处理的文件中。
  • 我试图更改为currencies.update,这是我的CurrencySchema,这并没有给我错误,但是raw的返回是{ n: 0, nModified: 0, ok: 1 },我认为是因为@ 987654333@ 返回一个数组,而不是逐个对象
  • 我看到您发布了控制台日志的输出,并且“货币”是您的整个文档,而不仅仅是我假设的单个实例。所以也许你需要updateMany
  • 完美,就是这样!非常感谢
猜你喜欢
  • 1970-01-01
  • 2016-01-29
  • 2019-10-13
  • 2019-03-22
  • 2015-02-12
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
相关资源
最近更新 更多