猫鼬:如何更新数组中的现有元素? [英] Mongoose: How to update an existing element in array?

查看:86
本文介绍了猫鼬:如何更新数组中的现有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法来更新数组中的现有元素,而不是三次获取数据库.如果您有任何想法,我将不胜感激.谢谢!

I was wondering if there is a better way to update an existing element in an array instead of fetching database three times. If you have any ideas I would appreciate it. Thank you!

    const creatStock = async (symbol, webApiData) => {
      try {
        // reversed array
        const webApiDataReversed = webApiData.reverse();

        const query = { symbol };
        const update = { $addToSet: { data: webApiDataReversed } };
        const options = { upsert: true, new: true };
        // create/update Stock
        const stockResult = await Stock.findOneAndUpdate(query, update, options);
        const lastElement = stockResult.data.length - 1;

        const updatePull = {
          $pull: { data: { date: stockResult.data[lastElement].date } },
        };
        // removes last date from data array
        await Stock.findOneAndUpdate(query, updatePull);
        // update Stock
        await Stock.findOneAndUpdate(query, update);
      } catch (ex) {
        console.log(`creatStock error: ${ex}`.red);
      }
    };

架构

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({
  symbol: {
    type: String,
    unique: true,
  },
  // Array of subdocuments
  data: [ChildSchemaData],
});

module.exports.Stock = mongoose.model('Stock', ParentSchemaSymbol);

输出

推荐答案

好吧,如果您不需要返回更新的文档,请尝试执行此操作-这只会返回写入结果,可以实现此目的在一个数据库调用中:

Well, if you don't need to return the updated document, Please try this one - this will just return a write result, with this things can be achieved in one DB call :

const creatStock = async (symbol, webApiData) => {
    try {
        // reversed array
        const webApiDataReversed = webApiData.reverse();
        const query = { symbol };

        await Stock.bulkWrite([
            {
                updateOne:
                {
                    "filter": query,
                    "update": { $pop: { data: 1 } }
                }
            }, {
                updateOne:
                {
                    "filter": query,
                    "update": {
                        $addToSet: {
                            data: webApiDataReversed
                        }
                    }
                }
            }
        ])
    } catch (ex) {
        console.log(`creatStock error: ${ex}`.red);
    }
};

参考: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆