Migrate Firebase Realtime Database to Firestore

后端 未结 4 540
甜味超标
甜味超标 2020-12-28 15:48

I am looking for the best way to migrate my apps database which is using firebase realtime database to the new Cloud Firestore database. I am confident for the project I am

4条回答
  •  [愿得一人]
    2020-12-28 16:12

    I just did this with a very basic node script and I hope it will serve as an example to the next one having this issue:

    require('firebase/firestore')
    const fs = require('fs')
    const { initializeApp, firestore } = require('firebase/app')
    
    const UID = 'asdfasdf' // UID of the user you are migrating
    
    initializeApp({
        apiKey: process.env.API_KEY,
        projectId: process.env.PROJECT_ID
    })
    
    // db.json is the downloaded copy from my firebasedatabase
    fs.readFile('db.json', (err, data) => {
        if (err) throw err
        const json = JSON.parse(data)
        const readings = json.readings[UID]
        const result = Object.values(readings)
        result.forEach(({ book, chapter, date }) =>
            // In my case the migration was easy, I just wanted to move user's readings to their own collection
            firestore().collection(`users/${UID}/readings`)
                .add({ date: firestore.Timestamp.fromDate(new Date(date)), chapter, book })
                .catch(console.error)
        )
        console.log('SUCCESS!')
    })
    

    Of course you can also iterate twice to do it for every user but in my case it was not needed :)

提交回复
热议问题