0
我正嘗試將一個json文件插入到mongodb中。當我直接在插入語句中輸入JSON時,它工作正常。但是,當我嘗試使用來自fs.readfile的數據變量(相同的JSON)插入失敗。當我使用變量而不是原始JSON時,我沒有收到錯誤,只是集合中的數據。代碼如下:使用變量將json文件插入到mongodb中
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var fs = require('fs');
var mydocuments = fs.readFile('testNames.json', 'utf8', function (err, data) {
var collection = db.collection('contactCollection');
collection.insert(data, function(err, docs) { //This insert Fails
collection.count(function(err, count) {
console.log(format("count = %s", count));
console.log("[" + data + "]");
db.close();
});
});
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var fs = require('fs');
var mydocuments = fs.readFile('testNames.json', 'utf8', function (err, data) {
var collection = db.collection('contactCollection');
collection.insert({firstname: "Bill"}, function(err, docs) { //This insert succeeds
collection.count(function(err, count) {
console.log(format("count = %s", count));
console.log("[" + data + "]");
db.close();
});
});