简体   繁体   中英

mongoose does not create document

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

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

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