简体   繁体   中英

Fail to run a migration on meteor using mongo's Bulk, Why?

I tried to update the Songs Collection with the migration below, but it just not work.It loop the Songs Collection and update a songId to all the document.I use mongo's Bulk since there are almost 2000 document inside the Songs Collection.

import { Songs } from '../imports/api/songs.js';

// omit the version 1

Migrations.add({
  version: 2,
  name: 'update the songId',
  up() {
    // This is how to get access to the raw MongoDB node collection that the Meteor server collection wraps
    const batch = Songs.rawCollection().initializeUnorderedBulkOp();

    // Mongo throws an error if we execute a batch operation without actual operations, e.g. when Lists was empty.
    let hasUpdates = false;

    // loop the Songs
    Songs.find({}).forEach(function(song,idx) {
      // add the songId to every song
      batch.find({ _id: song._id }).updateOne({ $set: { songId: idx } });
      hasUpdates = true;
    });

    if (hasUpdates) {
      // We need to wrap the async function to get a synchronous API that migrations expects
      const execute = Meteor.wrapAsync(batch.execute, batch);
      return execute();
    }
    return true;
  },
  down() {
    // the code to down ...
  }
});

The Songs Collection's scheme look like that:

{ 
  _id: type.mongoId,
  songName: type.string,
  lyric: type.arrayof(type.string),
  ...
}

using meteor v1.5 and percolate:migrations v1.0.2 ,on Osx .

But the Songs Collection's document song still don't have the songId after update to version 2.

Have i did somthing wrong?

From the cursor.forEach documentation :

function JavaScript A JavaScript function to apply to each document from the cursor. The <function> signature includes a single argument that is passed the current document to process.

There is no second argument, so your idx is undefined , thus { $set: { songId: <undefined> } } has no effect on collection records.

Just add let idx = 0; before Songs.find() , remove ,idx from forEach 's function signature and replace songId: idx with songId: ++idx .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM