mongoose不会创建文档

时间:2016-06-06 11:50:13

标签: node.js mongoose

我在ubuntu 16.04上使用nodejs(6.2.1)和mongoose(4.4.16)和mongodb(2.1.21)并创建一个注册表单但是当我提交mongoose时不会创建doucment并且请求继续等待。请帮我解决这个问题。以下是文件结构

观看次数位于app-server文件夹中,非常完美,因此我不包含该结构

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

路由/ 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;

模型/ 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');

模型/ 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);

控制器/ 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!');
        });
    }
};

此处console.log(req.body);输出我们通过表单

发送的内容

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

console.log(User)输出

{ [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 } } }

当我在终端上运行mongo并尝试use local show collections时,不提供任何输出

1 个答案:

答案 0 :(得分:3)

最后得到mongoose documentation

的解决方案
  

重要!如果您使用打开单独的连接   mongoose.createConnection()但尝试通过访问模型   mongoose.model('ModelName')它不会按预期工作,因为它是   没有连接到活动的数据库连接。在这种情况下访问你的   通过您创建的连接建立模型:

所以现在有两种方法

首先:更改 db.js

中的连接字符串

var mongoDB = mongoose.createConnection(mongoURI);

  mongoose.connect(mongoURI); 

  var mongoDB = mongoose.connection;

第二:更改 controllers / users.js

中使用.model()的行
var mongoose  = require( 'mongoose' );   
var conn = mongoose.createConnection('mongodb://localhost/loc8r'); 
var User = conn.model('User');