guys. I plan to create a signup page for my blog. But there's something wrong with the mongoose, I can't find the errors at all.
At first, I create a schema in mongo.js
,and exports a model as below:
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open',function(){
console.log("success open db!");
});
var Schema = mongoose.Schema;
//user schema
var userSchema = new Schema({
name: {
type: String
},
password: {
type: String
},
avatar: {
type: String
},
gender: {
type: String,
enum: ['m', 'f', 'x']
},
bio: {
type: String
}
});
//schema level index
userSchema.index({ name: 1 }, { unique: true });
//create user model
exports.User = mongoose.model('User', userSchema);
Then I call Model.create to save my data to the db,
var User = require('../lib/mongo').User;
module.exports = {
//save data
create: function(user) {
return User.create(user);
}
};
At last, I handle the promise which's from the model.create(),
var userModel = require('../models/users');
//save date
userModel.create(user)
.then(function (result) {
// 此 user 是插入 mongodb 后的值,包含 _id
user = result.ops[0];
// 将用户信息存入 session
delete user.password;
req.session.user = user;
// 写入 flash
req.flash('success', '注册成功');
// 跳转到首页
res.redirect('/posts');
})
.catch(function (e) {
// 用户名被占用则跳回注册页,而不是错误页
if (e.message.match('E11000 duplicate key')) {
req.flash('error', '用户名已被占用');
return res.redirect('/signup');
}
next(e);
});
});
but it didn't work, when I fill the from and submit, No user model was created and the website freezes... Are there wrong operation of mongoose? Thanks.
via Benny201
No comments:
Post a Comment