【问题标题】:nodejs/mongoDB - TypeError: Cannot read property 'collection' of undefinednodejs/mongoDB - 类型错误:无法读取未定义的属性“集合”
【发布时间】:2017-11-03 05:08:59
【问题描述】:

我正在尝试将表单数据提交到 mongoDB 数据库。但我很难做到。在我的 index.js 文件中出现“TypeError:无法读取未定义的属性‘集合’”错误 我的表单页面如下。

<form class = "profile" action = "/process" method="post">
<div class="form-group">
<label for="Fname">First Name: </label>
<input type="text" id="fName" name = "fName" class="form-control" placeholder="first name" >
</div>
<div class="form-group">
<label for="Lname">Last Name: </label>
<input type="text" id="lName" name = "lName" class="form-control" placeholder="last name" >
</div>
<div class="form-group">
<label for="email">Email : </label>
<input type="email" id="email" name = "email" class="form-control" placeholder="email.." required>
</div>
<div class="form-group">
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
</div>
<button type="submit" class="btn btn-primary" id="save">Submit</button>
</form>

index.js 文件是

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
const config = require('./config/database');
var routes  = require('./routes/main');
var db = mongo.db('localhost:27017/appointment');

mongoose.connect(config.database);
//check connection
mongoose.connection.on("connected",function(database){
db = database;
console.log('connected to db',+config.database);
});
var index = express();
//declare port
const port = 3000;

index.post('/process',function(req,res){
db.collection('appoint').save({firstName : req.body.fName,
 lastName : req.body.lName,
 email : req.body.email,
 phone : req.body.phone,
 dob : req.body.dob,
 gender : req.body.gender}, function(err,result){
    if(err) {   throw err; }
        console.log("saved to database");
        res.redirect('/thanks');

});
});
//connect to port
index.listen(port,function(){
console.log("listening to port ",port);
});

请让我知道我做错了什么。我被困在同一个地方一段时间了。

问候, 一月

【问题讨论】:

    标签: javascript node.js mongodb mean-stack


    【解决方案1】:

    检查下面的代码,代码中的回调函数返回错误和响应,而不是数据库连接。连接后,您需要使用用于连接的 var 来获取集合或创建新对象。

    var express = require('express');
    var path = require('path');
    var bodyParser = require('body-parser');
    var mongoose = require('mongoose');
    const config = require('./config/database');
    var routes  = require('./routes/main');
    var db = mongo.db('localhost:27017/appointment');
    
    mongoose.connect(config.database);
    //check connection
    mongoose.connection.on("connected",function(database){
        console.log('connected to db',+config.database);
    });
    
    var index = express();
    //declare port
    const port = 3000;
    
    index.post('/process',function(req,res){
        mongoose.collection('appoint').save({firstName : req.body.fName,
        lastName : req.body.lName,
        email : req.body.email,
        phone : req.body.phone,
        dob : req.body.dob,
        gender : req.body.gender}, function(err,result){
            if(err) {   throw err; }
                console.log("saved to database");
                res.redirect('/thanks');
    
            });
     });
    //connect to port
    index.listen(port,function(){
        console.log("listening to port ",port);
    });
    

    【讨论】:

    • 感谢您的回复。但它再次抛出同样的错误
    【解决方案2】:

    您的错误似乎是说db 未定义,因此当它尝试从db.collection, 获取.collection 时,它不知道要获取哪个collection。

    您是否尝试过将var db = mongo.db('localhost:27017/appointment'); 更改为var db = mongo.db('localhost:27017'); 和db.collection('appoint') 更改为db.collection('appointment')?

    另外,在mongoose.connect(config.database); 上,您可以检查是否有错误:

    mongoose.connect(config.database, (error) => {
      if(error) console.error(error);
      else console.log('connected to db ' + config.database);
    });
    

    希望这些帮助。

    【讨论】:

    • 感谢 ervi 的回复。我根据您的建议更改了代码。但仍然存在同样的错误。 :(
    • 您是否看到从console.error(error); 打印出错误,或者您是否看到从console.log 输出“已连接到数据库...”?
    • 您有appointment 的架构吗?如果你这样做,你可以在mongoose.connect 行之后添加var Appointment = mongoose.model('Appointment', appointmentSchema);。然后,您可以将db.collection('appointment').save 更改为Appointment.save。如果您没有架构并想使用现有集合,可以尝试stackoverflow.com/questions/5794834/…
    • 我有一个约会模式,我将 db.collection 修改为 Appointment.save 。但现在的错误是 TypeError:ointment.save is not a function.
    • ` var AppointmentSchema = new Schema({ firstName: { type: String, }, lastName:{ type: String, }, email:{ type: String, }, phone:{ type: Number, },出生日期:{类型:日期,},性别:{类型:字符串,}}); // 将模型名称和模式添加到 mongoose 模型。 var 约会 = mongoose.model('约会', AppointmentSchema);`
    猜你喜欢
    • 2018-10-04
    • 2018-06-12
    • 2023-01-28
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多