[英]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. 将数据插入collection中时遇到问题。它给出了无法读取未定义的collection属性的错误。 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);
Well I would suggest your to go this way. 好吧,我建议你这样走。
1- Don't use database name in when creating mongodburl
ie 1- creating mongodburl
时不要使用数据库名称
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. 现在,当您尝试与mongodb
服务器连接时,您将在回调函数中获得mongodb constructor
函数,因此您必须多添加一行代码。 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 这样,您将获得为database
college
定义的res
集合(我假设您已经通过诸如db.createCollection('res')
类的查询在数据库中定义了该集合),然后它应该可以工作了
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.