代码之家  ›  专栏  ›  技术社区  ›  Jee Mok ecanf

loopback-如何使用bulkupdate方法

  •  3
  • Jee Mok ecanf  · 技术社区  · 8 年前

    我目前正在使用loopback v3,希望一次在一个集合中插入许多记录;我发现了这个方法 bulkUpsert 从文件中( http://apidocs.loopback.io/loopback/#persistedmodel-bulkupdate )但我不知道怎么做。

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

    1 回复  |  直到 8 年前
        1
  •  3
  •   Jee Mok ecanf    8 年前

    有另一种方法 bulkUpdate 方法,在stackOverflow中找到 MongoDB aggregation on Loopback

    一个MIXIN可以很容易地创建和重复使用的模型。我的BulkPuxt 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

    推荐文章