简体   繁体   中英

export and import data from mongodb using node.js express

I want to export all data from my server to my local(also i don't have a backup so this will serve as a backup. So I used the below code to get the collection in a json format and save to the local.

I am using mongodb and node express.

dbName.find().exec(function(err, output){

var jsonOutput=JSON.stringify(output)

fs.writeFile('downloads/output.json', output, function (err) {
        if (err) {
            console.log(err)
            res.send('error')
        }
        else{
            var filename = 'res.json'
            var mimetype = 'application/json'

            res.setHeader('Content-disposition', 'attachment; filename=' + filename)
            res.setHeader('Content-type', mimetype)
            res.end(jsonOutput)
        }
    })
})

This gives me what I want. Now I want to process the json in my local machine so that my local data is in sync with the server.

  1. How to store all the data in bulk to the backend?
  2. I have few references between the schema, so will new '_id' be created hence affecting my references
  3. If you think this is not the right way to export the data, how can it be done using node express?

try to use mongodump or mongoexport . https://docs.mongodb.org/manual/core/backups/

mongoexport provide efficent way to export data from collection (by query if you want)

mongodump makes a full database dump (backup) so you can easily restore it anywhere, with the same ids, references, indexes. All your stuff

You can use node.js child_process.exec for running mongodump/mongoexport. You can use linux crontab for scheduling backups. So many ways to organize this with right tools

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