简体   繁体   中英

How to insert data into mongodb

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

    }]

图片

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM