-2

I am trying to submit the form data into mongoDB database. But i have trouble doing it. Getting "TypeError: Cannot read property 'collection' of undefined" error in my index.js file My form page is as follows.

<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>

the index.js file is

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

Please let me know what im doing wrong. I am stuck in the same place for a while.

Regards, Jan

janavvi
  • 19
  • 1
  • 7

2 Answers2

1

Check the code bellow, the callback function in your code returns error and response, not database connection. Once you connected you need to use the var you use to connect to get the collections or create new objects.

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

It seems your error is saying db is undefined, so when it tries to get .collection from db.collection, it doesn't know which collection to get.

Have you tried changing var db = mongo.db('localhost:27017/appointment'); to var db = mongo.db('localhost:27017'); and db.collection('appoint') to db.collection('appointment')?

Also, on mongoose.connect(config.database); you could check if there's an error:

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

Hope those help.

Ervi B
  • 770
  • 7
  • 16
  • Thanks ervi for the reply. I changed the code as per your suggestion. But still the same error prevails. :( – janavvi Jun 01 '17 at 22:47
  • Did you see error printed out from `console.error(error);` or do you see "connected to db..." output from the `console.log`? – Ervi B Jun 01 '17 at 22:49
  • Do you have a schema for `appointment`? If you do, you can add `var Appointment = mongoose.model('Appointment', appointmentSchema);` after `mongoose.connect` line. Then, you can change `db.collection('appointment').save` to `Appointment.save`. If you don't have a schema and want to use an existing collection, you could try https://stackoverflow.com/questions/5794834/how-to-access-a-preexisting-collection-with-mongoose – Ervi B Jun 01 '17 at 23:16
  • I have a schema for appointment and i modified db.collection to Appointment.save . but now the error is TypeError: appointment.save is not a function. – janavvi Jun 02 '17 at 13:48
  • ` var AppointmentSchema = new Schema({ firstName: { type: String, }, lastName:{ type: String, }, email:{ type: String, }, phone:{ type: Number, }, dob :{ type: Date, }, gender:{ type: String, } }); // add the model name and schema to the mongoose model. var appointment = mongoose.model('appointment', AppointmentSchema);` – janavvi Jun 02 '17 at 13:53
  • Try changing `new Schema` to `mongoose.Schema` so it knows where the schema should be created. Also, have you tried listing appointments out by doing `appointment.find`? Do you see the appointment collection in your mongodb if you just log in through the terminal? Are there documents in the collection? – Ervi B Jun 04 '17 at 18:43
  • It still errors saying "Type Error: appointment.save is not a function". There are no records getting saved in mongodb database via forms. Only if i try to insert records directly in mongodb it works. – janavvi Jun 04 '17 at 21:51