使用变量将json文件插入mongodb [英] Insert json file into mongodb using a variable
问题描述
我正在尝试将一个 json 文件插入到 mongodb 中.当我直接在插入语句中输入 JSON 时,它工作正常.但是,当我尝试使用 fs.readfile 中的数据变量(相同的 JSON)时,插入失败.我没有收到错误,只是当我使用变量而不是原始 JSON 时集合中的数据.这是代码..
I am trying to insert a json file into mongodb. When I enter the JSON directly into the insert statement, it works fine. However, when I try to use the data variable from fs.readfile (same JSON) The insert fails. I don't get an error, just now data in the collection when I use a variable instead of the raw JSON. Here's the code..
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();
});
});
推荐答案
您正在将文件内容编码为 UTF-8 字符串并尝试将其插入到数据库中.在插入数据之前,您需要使用 JSON.parse()
将字符串解析为 JSON.
You're encoding the file's contents as a UTF-8 string and attempting to insert that into the database. You need to parse the string as JSON by using JSON.parse()
before inserting the data.
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();
});
});
这篇关于使用变量将json文件插入mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!