猫鼬-深度嵌套对象中的推数组

时间:2020-08-28 10:59:25

标签: node.js arrays mongodb mongoose

我正在尝试将从Websocket获得的数据数组推入对象,在这种情况下为oneMin。那就是我想要的数组,而不是在kline之上和bybit之下

这就是我所看到的:

enter image description here

这是数据模型:

enter image description here

这是我当前拥有的代码:

ws.on('update', async function(message) {

  if (message.data !== null) {

    console.log(message)

    const Open = message.data[0].open;
    const High = message.data[0].high;
    const Close = message.data[0].close;
    const Low = message.data[0].low;
    const Volume = message.data[0].volume;
    const Timestamp = message.data[0].timestamp;

    const OHLCV = [Open, High, Low, Close, Volume, Timestamp]

    // var ohlc = new marketModel({ 
    //   bybit: {
    //             kline: {
    //               ethusd: {
    //                 oneMin: {
    //                   open: Open,
    //                   high: High,
    //                   low: Low,
    //                   close: Close,
    //                   volume: Volume,
    //                   timestamp:  Timestamp
    //                 },
    //               }
    //             }
    //           }
    // });
    // ohlc.push(function (data) {
    //   console.log("just saved to BTCUSDkline!");
    // });

    let setOHLCV = await marketModel.updateMany(
      {},
      {
        $addToSet: {
          bybit: {
            kline: {
              ethusd: {
                oneMin: {
                  open: Open,
                  high: High,
                  low: Low,
                  close: Close,
                  volume: Volume,
                  timestamp:  Timestamp
                },
              }
            }
          }
        },
      },
      {
        upsert: true,
        new: true,
      },
    );
    setOHLCV;
  }
});

我已经坚持了一段时间,所以任何帮助将是感激的!

如果我有一段时间以来第一次求助于SO!

编辑:因此,$addToSet代替了$setOnInsert,而是将对象下面的数组中的数据设置了!它甚至不替换它,它只是设置给定的第一个数组。现在我可以说$Set就像$setOnInsert一样,但是它代替了数据。

1 个答案:

答案 0 :(得分:0)

简单的解决方案,显然我应该这样写:

    let setOHLCV = await marketModel.findOneAndUpdate(
      {},
      {
        $push: {
          'bybit.kline.ethusd.oneMin': {            
            open: Open,
            high: High,
            low: Low,
            close: Close,
            volume: Volume,
            timestamp:  Timestamp
          }
        }
      },
      {
        upsert: true,
        new: true,
      },
    );
    setOHLCV;
  }
});