1

I am using nodejs (6.2.1) and mongoose(4.4.16) with mongodb(2.1.21) on ubuntu 16.04 and create a signup form but when I submit mongoose does not create the doucment and request keep waiting. Kindly help me to solve the issue. below are the file structure

views are on app-server folder which are perfect so I am not including that structure

app-api
├── controllers
│   └── users.js
├── models
│   ├── db.js
│   └── users.js
└── routes
    └── index.js

routes/index.js

var express = require('express');
var router = express.Router();
var ctrlUsers = require('../controllers/users');

router.get('/user', ctrlUsers.userInfo);
router.post('/signup', ctrlUsers.userSignup);

module.exports = router;

models/db.js

var mongoose  = require( 'mongoose' );
var mongoURI = 'mongodb://localhost/local';
var mongoDB = mongoose.createConnection(mongoURI);

mongoDB.on('connected', function (){
    // console.log("enviorment:" + process.env.NODE_ENV);
    // console.log("mongolab:" + process.env.MONGOLAB_URI);
    console.log('mongoose connected to ' + mongoURI);
});

mongoDB.on('disconnected', function (){
    console.log('mongoose disconnected ');
});

require('./users');

models/users.js

var mongoose = require('mongoose');
var Schema =  mongoose.Schema;

var userSchema = new Schema({
    username: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    email: {type: String, required: true},
    gender: {type: Boolean, "default": "m"},
    createdOn: {type: Date, "default": Date.now}
});

module.exports = mongoose.model('User', userSchema);

controllers/users.js

var mongoose  = require( 'mongoose' );
var User = mongoose.model('User');

module.exports.userInfo = function(req,res) {
    res.render('signup', {
        title: 'User List'
    });
};

module.exports.userSignup = function(req,res) {
    console.log(req.body);
    console.log(User);
    if (req.method == 'POST') {
        // console.log("[200] " + req.method + " to " + req.url);
        User.create({
            username: req.body.username,
            password: req.body.password,
            email: req.body.email
        },function (err, user) {
            console.log(err);
            if(err) handleError(err);
            console.log('User saved successfully!');
        });
    }
};

here console.log(req.body); outputs whetever we send through form

{ username: 'alpha', email: 'beta@gamma.com', password: 'delta' }

and console.log(User) outputs

{ [Function: model]
  hooks: Kareem { _pres: {}, _posts: {} },
  base: 
   Mongoose {
     connections: [ [Object], [Object] ],
     plugins: [],
     models: { User: [Circular], Location: [Object] },
     modelSchemas: { User: [Object], Location: [Object] },
     options: { pluralization: true } },
  modelName: 'User',
  model: [Function: model],
  db: 
   NativeConnection {
     base: 
      Mongoose {
        connections: [Object],
        plugins: [],
        models: [Object],
        modelSchemas: [Object],
        options: [Object] },
     collections: { users: [Object], locations: [Object] },
     models: { User: [Circular], Location: [Object] },
     config: { autoIndex: true },
     replica: false,
     hosts: null,
     host: null,
     port: null,
     user: null,
     pass: null,
     name: null,
     options: null,
     otherDbs: [],
     _readyState: 0,
     _closeCalled: false,
     _hasOpened: false,
     _listening: false },
  discriminators: undefined,
  schema: 
   Schema {
     paths: 
      { username: [Object],
        password: [Object],
        email: [Object],
        gender: [Object],
        createdOn: [Object],
        _id: [Object],
        __v: [Object] },
     subpaths: {},
     virtuals: { id: [Object] },
     singleNestedPaths: {},
     nested: {},
     inherits: {},
     callQueue: [ [Object], [Object] ],
     _indexes: [],
     methods: {},
     statics: {},
     tree: 
      { username: [Object],
        password: [Object],
        email: [Object],
        gender: [Object],
        createdOn: [Object],
        _id: [Object],
        id: [Object],
        __v: [Function: Number] },
     _requiredpaths: undefined,
     discriminatorMapping: undefined,
     _indexedpaths: undefined,
     s: { hooks: [Object], queryHooks: [Object] },
     options: 
      { typeKey: 'type',
        id: true,
        noVirtualId: false,
        _id: true,
        noId: false,
        validateBeforeSave: true,
        read: null,
        shardKey: null,
        autoIndex: null,
        minimize: true,
        discriminatorKey: '__t',
        versionKey: '__v',
        capped: false,
        bufferCommands: true,
        strict: true,
        pluralization: true } },
  collection: 
   NativeCollection {
     collection: null,
     opts: { bufferCommands: true, capped: false },
     name: 'users',
     collectionName: 'users',
     conn: 
      NativeConnection {
        base: [Object],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,
        hosts: null,
        host: null,
        port: null,
        user: null,
        pass: null,
        name: null,
        options: null,
        otherDbs: [],
        _readyState: 0,
        _closeCalled: false,
        _hasOpened: false,
        _listening: false },
     queue: [ [Object] ],
     buffer: true,
     emitter: 
      EventEmitter {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined } } }

when I run mongo on terminal and try use local show collections doesn't give any output

xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • what is this `models: { User: [Circular] ..}` – xkeshav Jun 06 '16 at 11:52
  • 1
    IMHO `local` is not replicable https://docs.mongodb.com/manual/reference/local-database. In the sense that the database you are writing to is probably not the one you are referring to on terminal. – kaushik94 Jun 06 '16 at 12:25
  • okay. I have created db `loc8r` and change it to `loc8r` and still same issue – xkeshav Jun 06 '16 at 12:30
  • What output are you getting ? – kaushik94 Jun 06 '16 at 12:40
  • I have already pasted the output in Question – xkeshav Jun 06 '16 at 12:46
  • Dude I'm talking about the output when `show collections` lol – kaushik94 Jun 06 '16 at 12:47
  • show collections not displaying anything, I think it will display when there would be atlease one document created – xkeshav Jun 06 '16 at 12:50
  • it's really frustrating when try to learn the basic and stuck on first step :( also there is no clear solutions on the web. someone using `module.exports = mongoose.model(...)` in schema file while someone using `require(filename)` no clear difference at all – xkeshav Jun 06 '16 at 12:50
  • I've been through that, you'll get over it. See this http://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js. Okay so try one more thing, just uncomment the `console.log` in your code and see if the request was going ? – kaushik94 Jun 06 '16 at 12:56
  • request is going my friend, that's why `console.log` output the data. I havn't commented `console.log` – xkeshav Jun 06 '16 at 13:00

1 Answers1

5

Finally got the solution from mongoose documentation

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

So now there are two approaches

First: Change the connection string in db.js

from

var mongoDB = mongoose.createConnection(mongoURI);

to

  mongoose.connect(mongoURI); 

  var mongoDB = mongoose.connection;

Second: Change the lines where using .model() in controllers/users.js

var mongoose  = require( 'mongoose' );   
var conn = mongoose.createConnection('mongodb://localhost/loc8r'); 
var User = conn.model('User');
xkeshav
  • 53,360
  • 44
  • 177
  • 245