首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >回环-如何使用bulkUpdate方法

回环-如何使用bulkUpdate方法
EN

Stack Overflow用户
提问于 2018-07-07 06:05:30
回答 1查看 2.5K关注 0票数 3

我目前正在使用Loopback v3,并且希望在一个集合中一次插入许多记录;我从文档(http://apidocs.loopback.io/loopback/#persistedmodel-bulkupdate)中找到了这个方法bulkUpsert,但我想不出如何使它工作。

如何从文档中提到的updates方法创建createUpdates()数组?有人能帮我举一个使用这种方法的简单例子吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-02 02:18:16

有另一种方法来执行bulkUpdate方法,可以在Stackoverflow 回环上的MongoDB聚合中找到。

可以很容易地在模型上创建和重用混合器。我的bulkUpsert mixin示例代码如下:

代码语言:javascript
复制
Model.bulkUpsert = function(body, cb) {
    try {
      Model.getDataSource().connector.connect(async (err, db) => {
        if (err) {
          return cb(err);
        }

        // Define variable to hold the description of the first set of validation errors found
        let validationErrors = '';

        // Build array of updateOne objects used for MongoDB connector's bulkWrite method
        const updateOneArray = [];

        // Loop through all body content and stop the loop if a validation error is found
        const hasError = body.some(row => {
          // Check if it is a valid model instance
          const instance = new Model(row);
          if (!instance.isValid()) {
            // A validation error has been found
            validationErrors = JSON.stringify(instance.errors);
            // By returning true we stop/break the loop
            return true;
          }

          // Remove ID in the row
          const data = JSON.stringify(row);
          delete data.id;

          // Push into the update array
          updateOneArray.push({
            updateOne: {
              filter: { _id: row.id },
              update: { $set: Object.assign({ _id: row.id }, data) },
              upsert: true
            }
          });

          // No validation error found
          return false;
        });

        // Check if a validation error was found while looping through the body content
        if (hasError) {
          return cb(new Error(validationErrors));
        }

        // No validation data error was found
        // Get database collection for model
        const collection = db.collection(Model.name);
        // Execute Bulk operation
        return collection.bulkWrite(updateOneArray, {}, (err, res) => {
          // Check if the process failed
          if (err) {
            console.err('The bulk upsert finished unsuccessfully', err);
            return cb(err);
          }

          // Check if there were errors updating any record
          if (res.hasWriteErrors()) {
            console.error(`The bulk upsert had ${res.getWriteErrorCount()} errors`, res.getWriteErrors());
          }

          // Finished successfully, return result
          return cb(null, {
            received: body.length,
            handled: res.upsertedCount + res.insertedCount + res.matchedCount
          });
        });
      });
    }
    catch (err) {
      console.error('A critical error occurred while doing bulk upsert', err);
      return cb(err);
    }
    return null;
  };

参考文献:Mongodb查询文档

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51220436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档