如何在节点中通过mongojs将.json文档插入mongo服务器 [英] how to insert a .json document to mongo server by mongojs in node

查看:94
本文介绍了如何在节点中通过mongojs将.json文档插入mongo服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是nodeJS和MongoDB的新手. 我有以下代码:

I'm new with nodeJS and MongoDB. I have this code:

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字符串.

no data insered to the mongodb, and I've got no error. the both console.log(data) print the json string as well.

推荐答案

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

Try to parse it as JSON before inserting it into the document

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

这篇关于如何在节点中通过mongojs将.json文档插入mongo服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆