0

I am trying to insert a record to the mongodb blogdb hosted at port 27017 using nodeJS.

I keep getting the error in the image. The error I'm getting is "localhost:27017 socket closed"

The record I am trying to enter is

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

Here is my db.js file which I have executed as node 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

4
  • What the "escape" slashing here? If you take all the \` out then everything is okay. And of course the [1][1] on the end. Which what is that about? Commented Aug 3, 2015 at 10:59
  • Can you explain your last line ][1]][1] and the \[post1\]? Commented Aug 3, 2015 at 10:59
  • 1
    first, can you please check if mongo is running using command "mongod" ? Commented Aug 3, 2015 at 11:01
  • The socket closed error indicates the database cannot be reached. Can you verify that the database is running and if it is, are you on a Windows based machine? You could have an issue with Mongo becoming locked. Commented Aug 3, 2015 at 12:50

1 Answer 1

2

First of all your JSON is incorrect. It should not have comma(',') after last element in your JSON(which in your case is "likes:86"). Below is correct JSON:

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

Please try after this. Please report in case you still get the issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.