【问题标题】:Insert json file into mongodb using a variable使用变量将json文件插入mongodb
【发布时间】:2014-10-27 13:42:04
【问题描述】:

我正在尝试将 json 文件插入 mongodb。当我将 JSON 直接输入到 insert 语句中时,它工作正常。但是,当我尝试使用 fs.readfile 中的数据变量(相同的 JSON)时,插入失败。我没有收到错误,只是当我使用变量而不是原始 JSON 时集合中的数据。这是代码..

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();
        });
    });

【问题讨论】:

    标签: javascript json node.js mongodb


    【解决方案1】:

    您将文件的内容编码为 UTF-8 字符串并尝试将其插入数据库。在插入数据之前,您需要使用 JSON.parse() 将字符串解析为 JSON。

    var fs = require('fs');
    var mydocuments = fs.readFile('testNames.json', 'utf8', function (err, data) {
    var collection = db.collection('contactCollection');
     collection.insert(JSON.parse(data), function(err, docs) { // Should succeed
        collection.count(function(err, count) {
            console.log(format("count = %s", count));
            console.log("[" + data + "]" );
            db.close();
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多