gpt4 book ai didi

node.js - 无法捕获 Mongoose 模型保存的错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:34 24 4
gpt4 key购买 nike

我有一个简单的用户架构:

/schemas/user.js

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

var userSchema = new Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
group: String,
created_at: Date,
updated_at: Date
});

var User = mongoose.model(
'User',
userSchema
);

module.exports = User;

以及一个带有能够创建用户的表单的索引页。如果保存无法正常工作,我想向用户显示一条闪存消息。我知道这样做的前提是在 get 路由中为消息创建一个位置,如果消息存在,则渲染一个包含该消息的 dom 元素。不幸的是,我所能管理的就是使服务器崩溃并接收:

错误消息

events.js:160
throw er; // Unhandled 'error' event
^
BulkWriteError: E11000 duplicate key error collection: test.users index: email_1 dup key: { : "test@gmail.com" }
at /home/bob/sites/mysite.ca/projects/login/node_modules/mongodb/lib/bulk/unordered.js:528:15
at handleCallback (/home/bob/sites/mysite.ca/projects/login/node_modules/mongodb/lib/utils.js:128:55)
at resultHandler (/home/bob/sites/mysite.ca/projects/login/node_modules/mongodb/lib/bulk/unordered.js:454:5)
at /home/bob/sites/mysite.ca/projects/login/node_modules/mongodb-core/lib/connection/pool.js:541:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

/routes/index.js

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('index.js db connected!');
});

var User = require('../schemas/user');

router.post('/create', function(req, res, next) {
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
user.save(function(error) {
if (error) console.log(error);
console.log('User ' + user.username + ' successfully created!');
});
});

/* GET home page. */
router.get('/', function(req, res, next) {
res.render(
'index',
{
title: 'Express'
}
);
});

module.exports = router;

如何捕获此错误并处理它而不是导致 Node 服务器崩溃?

最佳答案

我认为你的代码是正确的,你只需要在 app.js 中创建 mongoose 连接一次,默认情况下 mongoose 使用 5 个并发连接的池,不需要创建连接在每个路由器中:

app.js

...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
...

routes/index.js

并且您必须向客户端发送响应以终止请求-响应周期,否则客户端将被挂起:

var express = require('express');
var router = express.Router();
var User = require('../schemas/user');
...

router.post('/create', function(req, res, next) {
var user = new User(req.body);
user.save(function(err, user) {
if (err) return res.json(err);
res.send('User ' + user.username + ' successfully created!');
});
});

关于node.js - 无法捕获 Mongoose 模型保存的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48159862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com