rest - Loopback - 如何使用 bulkUpdate 方法

标签 rest loopback

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

如何根据文档中提到的 createUpdates() 方法创建 updates 数组?谁能帮我举一个使用此方法的简单示例?

最佳答案

有另一种方法可以执行 bulkUpdate 方法,可在 Stackoverflow 中找到 MongoDB aggregation on Loopback

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

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 query documentation

关于rest - Loopback - 如何使用 bulkUpdate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51220436/

相关文章:

wcf - 如何在 Restful WCF 服务中管理 session

node.js - 如何在 CentOS 上运行的 Apache HTTP 服务器上设置 Loopback nodeJS 后端

启用 TCP_NODELAY 的 Linux 环回性能

node.js - Loopback异步数据调用Nodejs

java - EJB:自定义身份验证和授权

c# - HttpGet 中查询字符串的替代方案用于发送数据?

node.js - Node js 原始查询返回匿名数据类型

windows - 如何为 UWP Windows 10 应用启用环回作为 TCP 服务器?

基于标准 WCF 服务的 RESTful WCF 服务

java - Jest ElasticSearch 中的 retry_on_conflict