简体   繁体   中英

MongoDB collection error undefined

i am facing an issue while inserting data into collection.it gives an error of cannot read property of collection undefined. provide a solution of it i try my best. here is my code.

var http = require('http');
var fs = require('fs');

var querystring = require('querystring');
var MongoClient = require('mongodb').MongoClient;
var url ="mongodb://127.0.0.1:27017/college";

var port = 4000;
http.createServer((req,res) => {

    if(req.url==="/form")
    {
        res.writeHead(200,{"Content-Type": "text:html"});
        fs.createReadStream("./public/form.html" , "UTF-8").pipe(res);
    }
    if(req.method==="POST")
    {
        var data = " ";
        req.on("data", function(chunk) 
        {
            data += chunk;
        });
        req.on("end" , function(chunk){

             MongoClient.connect(url , function(err,db){
                 if(err) throw err;
                 var q = querystring.parse(data).
                 db.collection('res').insertOne(q,function(err,res){
                    if(err) throw err;
                    console.log("data is insert");
                    db.close();
                 });

             })
        });
    }
}).listen(port);
console.log(port);

here is erro i am facing

Well I would suggest your to go this way.

1- Don't use database name in when creating mongodburl ie

replace

var url ="mongodb://127.0.0.1:27017/college";

with

var url ="mongodb://127.0.0.1:27017/";

And now when you try to connect with mongodb server you'll get mongodb constructor in the callback function so you'll have to add one extra line of code. Something like below

 MongoClient.connect(url , function(err,dbC){
             if(err) throw err;
            var db = dbC.db("college");
             var q = querystring.parse(data).
             db.collection('res').insertOne(q,function(err,res){
                if(err) throw err;
                console.log("data is insert");
                db.close();
             });

         })

This way you'll get res collection defined for the database college (I am assuming you've already defined that collection in your database with some query like db.createCollection('res') ) and then it should work

Thanks

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