猫鼬不创建文档 [英] mongoose does not create document

查看:58
本文介绍了猫鼬不创建文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ubuntu 16.04上将nodejs(6.2.1)和mongoose(4.4.16)与mongodb(2.1.21)一起使用,并创建了注册表单,但是当我提交mongoose时不会创建文档,并且请求保持等待状态.请帮助我解决问题.下面是文件结构

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

此处console.log(req.body);输出我们通过表单发送的信息

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

{ 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没有给出任何输出时

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

推荐答案

最后从 mongoose documentation

重要!如果您使用打开了一个单独的连接 mongoose.createConnection(),但尝试通过以下方式访问模型 mongoose.model('ModelName')不能正常工作,因为它是 没有连接到活动的数据库连接.在这种情况下,请访问您的 通过您创建的连接进行建模:

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:

所以现在有两种方法

首先:在 db.js

来自

var mongoDB = mongoose.createConnection(mongoURI);

  mongoose.connect(mongoURI); 

  var mongoDB = mongoose.connection;


第二:更改 controllers/users.js


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

这篇关于猫鼬不创建文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆