Reputation: 99
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)
}
});
}]
Upvotes: 0
Views: 4664
Reputation: 644
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.
Upvotes: 2