2

I have a large nested object defined as a single document from a mobile app that I want to backup to MongoDB via an Express-powered REST API. This is not something that will be done often or in real time, so I don't need to build a full transactional API, I'd rather just backup and restore as a single action if possible.

Doing this on the command line is simple, but I'd like to build a REST API to do this programmatically. Example command line:

mongoimport --db workouttest --collection workouts --file workouts.json --jsonArray

Sample JSON used in the mongoimport example above, defined by the following schema:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var workoutSchema   = new Schema({
    name: String,
    startDate: Date,
    userProfile: {
        age: Number,
        name: String,
        bodyWeight: Number
    },
    program: [{
        name: String,
        goal: Number,
        notes: String,
        workoutDiary: [{
            date: Date,
            sets: [{
                repCount: Number,
                weight: Number
            }]
        }]
    }]
});

module.exports = mongoose.model('Workout', workoutSchema);

1 Answer 1

1

Solution on windows:-

Step 1: Create a bat file

File name : "myimport.bat"

cd D:\workspaces\mongodb_node
mongoimport -d localhost -c workouts < workouts.json
echo "completed...."
exit /b 0

Step 2:

Please ensure to change the database name and bat file name accordingly

var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, ReplSetServers = require('mongodb').ReplSetServers, ObjectID = require('mongodb').ObjectID, Binary = require('mongodb').Binary, GridStore = require('mongodb').GridStore, Grid = require('mongodb').Grid, Code = require('mongodb').Code,
assert = require('assert');

var db = new Db('localhost', new Server('localhost', 27017));

db.open(function(err, db) {
var spawn = require('child_process').spawn;
var bat = spawn('cmd.exe', ['/c', 'myimport.bat']);
bat.stdout.on('data', (data) => {
          console.log("Commands ...");
        });

        var exec = require('child_process').exec;
        exec('myimport.bat', (err, stdout, stderr) => {
              if (err) {
                console.error(err);             
              }
              console.log("Executing ...");
            });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.