prdtuty
prdtuty

Reputation: 532

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?

Upvotes: 2

Views: 4435

Answers (1)

vmkcom
vmkcom

Reputation: 1668

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

Upvotes: 2

Related Questions