0
var fs = require("fs")
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    const testFolder = 'dbbackups';


    fs.readdir(testFolder, (err, files) => {
        files.forEach(file => {
            //console.log(file);
            fs.readFile(testFolder+"/"+file, 'utf8', function (err,data) {
                if (err) {
                    return console.log(err);
                }
                console.log("************************************************");
                console.log(file);
                console.log(data);
                console.log("************************************************");
                var dbo = db.db("mydb");
                var myobj = data;
                dbo.collection(file.slice(0, -4)).insertOne(myobj, function(err, res) {
                    if (err) throw err;
                    console.log("1 document inserted");
                    db.close();
                });

            });
           // console.log(file.slice(0, -4));
        });
    })

});

this is my nodejs code .in this code i will read available files in folder and save content of this files to mongo db . this files content mongo documents

{
    "_id" : ObjectId("5a8be310e08d2d9fc276a3ac"),
    "name" : "facener",
    "firstname" : "facener",
    "lastname" : "facener",
    "username" : "facener",
    "password" : "$2a$10$nWPLXb4p5wEWvk3g.YRdfOw7d1kAvPuvd45P.1AEaJyv9E0TtZfAe",
    "multi_login" : true,
    "phoneNumber" : {
        "verified" : false,
        "type" : "phone",
        "contact" : "077441234567"
    },
    "email" : {
        "verified" : true,
        "type" : "phone",
        "contact" : "facener"
    },
    "user_meta" : {
        "role" : "superadmin"
    },
    "systemuser" : true,
    "company" : 1,
    "tenant" : 1,
    "client_scopes" : [ 
        {
            "consoleName" : "OPERATOR",
            "menus" : [ 
                {
                    "menuItem" : "TENANTMONITOR",
                    "menuAction" : [ 
                        {
                            "scope" : "tenant",
                            "read" : true,
                            "write" : true,
                            "delete" : true
                        }
                    ]
                }
            ]
        }
    ],
    "user_scopes" : [],
    "contacts" : [],
    "__v" : 0,
    "birthday" : ISODate("1989-12-24T00:00:00.000Z"),
    "gender" : "male",
    "avatar" : "",
    "address" : {
        "number" : "77",
        "street" : "7 Road",
        "city" : "7 03",
        "province" : "pp",
        "country" : "usa",
        "zipcode" : "00300"
    },
    "verified" : true,
    "group" : ObjectId("58466e3e9e5db600019768bb"),
    "locale" : "en",
    "app_meta" : {
        "subject" : "test2",
        "priority" : "urgent",
        "description" : "test2"
    },
    "Active" : true,
    "security_level" : 1
}

but my nodejs app throws errors as below

 if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk();
                                          ^

TypeError: Cannot create property '_id' on string '{
    "_id" : ObjectId("590091708ef913c5096e5494"),

as i understood its because that json file content mongo specific object how can i fix this issue this files can be random data .what is the best way to avoid this issue . is there any way to use mongo compatible json objects in nodejs app.

gamage
  • 19
  • 7
  • You also have a `db.close()` in there and lots of other problems. But your JSON is a "string" and not a JavaScript object, so you need to call `JSON.parse()` before inserting it. I suggest maybe searching https://www.google.com/search?q=nodejs+insert+json+to+mongodb and reading some things before you go much further. – Neil Lunn May 23 '18 at 09:32
  • yes can insert simple json objects but cannot insert mongodb document – gamage May 23 '18 at 09:35
  • Read the error. **on "string"** `{ "_id" : ObjectId("590091708ef913c5096e5494"),` is a "string" that you need to `JSON.parse()`. It's NOT a "document" yet until you `parse` it. Read the link above your question, since that is what it is there for. – Neil Lunn May 23 '18 at 09:38
  • I should also add that `ObjectId(` has no place in a JSON file. I suspect you or someone dumped this from output of the `mongo` shell. That `ObjectId()` is a wrapper for a JavaScript function and not valid JSON. See also [MongoDB Extended JSON](https://docs.mongodb.com/manual/reference/mongodb-extended-json/) in the core documentation for a description of what valid JSON here would actually be and how it can be obtained from MongoDB tools. – Neil Lunn May 23 '18 at 09:47

0 Answers0