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));
});
})
});
这是我的nodejs代码。在此代码中,我将读取文件夹中的可用文件并将此文件的内容保存到mongo db。 这个文件内容是mongo文件
{
"_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
}
但我的nodejs app会抛出错误,如下所示
if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk();
^
TypeError: Cannot create property '_id' on string '{
"_id" : ObjectId("590091708ef913c5096e5494"),
正如我所理解的那样,因为json文件内容是mongo的特定对象
我如何解决这个问题这个文件可以是随机数据。什么是避免这个问题的最佳方法。有没有办法在nodejs应用程序中使用mongo兼容的json对象。