Updating type date to isoDate

;(async () => {
try {
// ensure you update your host information below!
const host = “mongodb://<your atlas connection uri from your .env file”
const client = await MongoClient.connect(
host,
{ useNewUrlParser: true },
)
const mflix = client.db(“mflix”)

// TODO: Create the proper predicate and projection
// add a predicate that checks that the `lastupdated` field exists, and then
// check that its type is a string
// a projection is not required, but may help reduce the amount of data sent
// over the wire!
const predicate = { lastupdated: { $lastupdated: true } }
const projection = {}
const cursor = await mflix
  .collection("movies")
  .find(predicate, projection)
  .toArray()
const moviesToMigrate = cursor.map(({ _id, lastupdated }) => ({
  updateOne: {
    filter: { _id: ObjectId(_id) },
    update: {
      $set: { lastupdated: new ISODate(lastupdated)}
    },
  }

}));
console.log('hjhjh',lastupdated);
console.log(
  "\x1b[32m",
  `Found ${moviesToMigrate.length} documents to update`,
)
// TODO: Complete the BulkWrite statement below
const { modifiedCount } = await mflix.collection("movies").BulkWrite(moviesToMigrate);
console.log("\x1b[32m", `${modifiedCount} documents updated`)
client.close()
process.exit(0)

} catch (e) {
if (
e instanceof MongoError &&
e.message.slice(0, “Invalid Operation”.length) === “Invalid Operation”
) {
console.log("\x1b[32m", “No documents to update”)
} else {
console.error("\x1b[31m", Error during migration, ${e})
}
process.exit(1)
}
})()

is it correct to bulkwrite

Hello aparna4,
I have just completed this Ticket. Here is my implementation.
;(async () => {
try {

        const host = "mongodb+srv://m220student:m220password@mycluster.mongodb.net" //It is your connection uri specified in .env file
        const client = await MongoClient.connect(
          host,
          { useNewUrlParser: true },
        )
        
        const mflix = client.db("mflix")
        
        const predicate = { lastupdated: { $exists: true, $type: "string" } }
        const projection = { projection: { lastupdated: 1 } }
        const cursor = await mflix
          .collection("movies")
          .find(predicate, projection)
          .toArray()
        
        const moviesToMigrate = cursor.map(({ _id, lastupdated }) => ({
          updateOne: {
            filter: { _id: ObjectId(_id) },
            update: {
              $set: { lastupdated: new Date(Date.parse(lastupdated)) },
            },
          },
        }))
        console.log(
          "\x1b[32m",
          `Found ${moviesToMigrate.length} documents to update`,
        )
        
        const { modifiedCount } = await mflix.collection("movies").bulkWrite(moviesToMigrate)

        console.log("\x1b[32m", `${modifiedCount} documents updated`)
        client.close()
        process.exit(0)
      } catch (e) {
        if (
          e instanceof MongoError &&
          e.message.slice(0, "Invalid Operation".length) === "Invalid Operation"
        ) {
          console.log("\x1b[32m", "No documents to update")
        } else {
          console.error("\x1b[31m", `Error during migration, ${e}`)
        }
        process.exit(1)
      }
    })()

Determining test suites to run…Setup Mongo Connection
FAIL test/migration.test.js
Migration
✕ migration (60ms)

● Migration › migration

expect(received).not.toBeNull()

Received: null

  13 |     })
  14 |     console.log('dddeded',movie);
> 15 |     expect(movie).not.toBeNull()
     |                       ^
  16 |   })
  17 | })
  18 | 

  at toBeNull (test/migration.test.js:15:23)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:296:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
  at step (node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
  at node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13

console.log test/migration.test.js:14
this is what the error is it is from test file

I think you need to change the host name.
const host = “mongodb://<your atlas connection uri from your .env file”
to your connection uri

i did that mongodb+srv://m220student:m220password@mflix-1dkeu.mongodb.net

Are you run your script by,
node src/migrations/movie-last-updated-migration.js

yup
the error is here in migration.test.js file
test(“migration”, async () => {
const movie = await MoviesDAO.movies.findOne({
_id: ObjectId(“573a1391f29313caabcd8526”),
lastupdated: { $type: “date” },
})
console.log(‘dddeded’,movie);// this returns null
expect(movie).not.toBeNull()
})

Actually, I also got the same error. Run the test after running your script will pass your test.

1 Like

node movie-last-updated-migration.js
module.js:540
throw err;
^

Error: Cannot find module ‘/Users/aparna/Desktop/mflix-js/movie-last-updated-migration.js’
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3

Open the folder in which movie-last-updated-migration.js exists.
Then open the terminal in that folder and then,
run node movie-last-updated-migration.js

thank you so much i got it

Is your Ticket completed?

yup ticket is completed

Ok. :slightly_smiling_face: