如何将数据插入mongodb

时间:2015-08-03 10:56:44

标签: javascript node.js mongodb

我正在尝试使用nodeJS将记录插入到端口27017托管的mongodb blogdb。

我一直在图片中收到错误。我得到的错误是“ localhost:27017 socket closed

我想要输入的记录是

var post1 = {
    title:"Flight 2012",
    by:"posiden",
    tags:["planes","movies","pilot"],
    likes:86,
};

这是我作为节点db.js

执行的db.js文件
[![//require mongodb native drivers
var mongodb = require('mongodb');
//getting the mongo client interface to connect witha  mongodb server
var MongoClient = mongodb.MongoClient;
//connection url of the database
var url = 'mongodb://localhost:27017/blogdb';
//use the connect method to conenct to the server
MongoClient.connect(url,function(err,db){

    if(err){
        console.log("Unabel to connect to mongo server ERROR : " ,err);
    }else {
        console.log("Connection sucesful to ", url);

        var collection = db.collection('posts');
        var post1 = {
            title: "Flight 2012",
            by: "posiden",
            tags: \["planes", "movies", "pilot"\],
            likes: 86,
        };
        collection.insert(\[post1\], function (err, result) {
            if (err) {
                console.log("ERROR ", err);
            }
            else {
                console.log("SUCCESS INSERTED in to users collection _is are ", result.length, result)
            }
        });

    }]

Image

1 个答案:

答案 0 :(得分:2)

首先,您的JSON不正确。它不应该在你的JSON中的最后一个元素之后有逗号(',')(在你的情况下是"喜欢:86")。以下是正确的JSON:

var post1 = {
    title:"Flight 2012",
    by:"posiden",
    tags:["planes","movies","pilot"],
    likes:86
};

请在此之后尝试。如果您仍然遇到问题,请报告。