json - 如何通过 Node 中的 mongojs 将 .json 文档插入到 mongo 服务器

标签 json node.js fs mongojs

我是 nodeJS 和 MongoDB 的新手。 我有这段代码:

var fs = require('fs');
var mongojs = require('mongojs');
var db = mongojs('monitor', ["configurations"]);

fs.readFile('json/object1.json', 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);

    db.configurations.insert(data, function(err, doc) {
        console.log(data);
    if(err) throw err;
  });
});

没有数据插入到 mongodb,我也没有错误。 两个 console.log(data) 也打印 json 字符串。

最佳答案

在将其插入文档之前尝试将其解析为 JSON

fs.readFile('json/object1.json', 'utf8', function (err, data) {
    if (err) throw err;
    console.log(data);
    var json = JSON.parse(data);

    db.configurations.insert(json, function(err, doc) {
        console.log(data);
        if(err) throw err;
    });
});

关于json - 如何通过 Node 中的 mongojs 将 .json 文档插入到 mongo 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31109764/

相关文章:

json - Postgres : How to achieve json_agg like functionality on json_object_keys

node.js - 在 node.js express 中访问 HTTP 服务器对象

node.js - 无法让 git 停止跟踪 package-lock.json

javascript - 访问对象中数据的复杂性

node.js - 模块内的相对文件系统写入路径

javascript - 解析字符串以提取JSON数组

json - Dart 对象 -> JSON 字符串无法转换为 JSON

node.js - NodeJS,更改文件位置

javascript - 在 AngularJS 中读取非 JSON 文件

javascript - node.js fs.readdir 不显示目录中的任何文件