我正在遵循“通过构建10个项目来学习nodejs”的教程。我的编码方式与我的讲师相同,但是当我向mongo数据库中添加新用户时,除了{"__v": 0}
我正在遵循“通过构建10个项目来学习nodejs”的教程。我的编码方式与我的讲师相同,但是当我向mongo数据库中添加新用户时,除了{"__v": 0}
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
},
email: {
type: String
},
name: {
type: String
},
profileimage: {
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.createUser = function(newUser,callback){
newUser.save(callback);
}
//这是即时消息创建用户的方式
router.post('/register', function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
var multer = require('multer');
var upload = multer({ dest: './uploads' });
// Check for Image Field
if(req.files && req.files.profileimage){
console.log('uploading File...');
// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileImage: profileImageName
});
// Create User
User.createUser(newUser, function(err, user){
if(err)throw err;
console.log(user);
});
//Success Message
req.flash('success', 'You are now registered and may log in');
res.location('/');
res.redirect('/');
//}
});
请检查代码,看看我哪里出错了
答案 0 :(得分:1)
这将导致猫鼬意味着您正在保存一个没有值的用户。 您需要保存一个用户,例如:
let user= new User({
userName: value,
userPassword: value
});
user.save();
或显示更多您如何尝试传递值的信息,以便我们可以检查出最佳方法。
答案 1 :(得分:0)
使用您的自定义方法createUser
let userModel= new User();
let data = {username:'alpha',password:'beta',name:'gamma'};
userModel.createUser(data,(err,doc) => {
if(err){
console.log(err);
}
console.log('saved');
})
答案 2 :(得分:0)
只需在创建后添加newUser.save()