猫鼬不创建文档
Posted
技术标签:
【中文标题】猫鼬不创建文档【英文标题】:mongoose does not create document 【发布时间】:2016-10-06 00:26:18 【问题描述】:我在 ubuntu 16.04 上使用 nodejs (6.2.1) 和 mongoose(4.4.16) 和 mongodb(2.1.21) 并创建一个注册表单,但是当我提交 mongoose 时不会创建文档并请求继续等待。请帮助我解决问题。以下是文件结构
views 位于完美的 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;
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);
控制器/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
没有给出任何输出
【问题讨论】:
这是什么models: User: [Circular] ..
恕我直言local
不可复制docs.mongodb.com/manual/reference/local-database。从某种意义上说,您正在写入的数据库可能不是您在终端上引用的那个。
好的。我创建了 db loc8r
并将其更改为 loc8r
仍然是同样的问题
你得到了什么输出?
我已经在 Question 中粘贴了输出
【参考方案1】:
终于从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');
【讨论】:
以上是关于猫鼬不创建文档的主要内容,如果未能解决你的问题,请参考以下文章