我正在创建一个新用户,并检查该用户电子邮件以前是否存在。如果不是,那么它将创建一个新用户并保存它。我该如何纠正我收到的验证错误?
我已经尝试过通过将名称设置为不需要的方式进行尝试。但这仍然行不通。
这是我的用户模型。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//Declaring User Model
const UserSchema = new Schema({
name: {
type: String,
required: true
},
password: {
type: String,
required: true
},
email: {
type: String,
required: true
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model("users", UserSchema);
这是用户路线。
router.post("/register", (req, res) => {
User.findOne({ email: req.body.email }).then(user => {
if (user) {
return res.status(400).json({ email: "email already exists" });
} else {
const avatar = gravatar.url(req.body.email, {
s: "200", //size
r: "pg", //rating
d: "mm" //default
});
const newUser = new User();
const newUser = {
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
};
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
});
我希望它会被存储。这是我得到的错误。
{ ValidationError: users validation failed: name: Path `name` is required.
at ValidationError.inspect (G:\devconnector\node_modules\mongoose\lib\error\validation.js:59:24)
at formatValue (internal/util/inspect.js:493:31)
at inspect (internal/util/inspect.js:191:10)
at Object.formatWithOptions (util.js:84:12)
at Console.(anonymous function) (console.js:191:15)
at Console.log (console.js:202:31)
at newUser.save.then.catch.err (G:\devconnector\routes\api\users.js:39:35)
at process._tickCallback (internal/process/next_tick.js:68:7)
errors:
{ name:
{ ValidatorError: Path `name` is required.
at new ValidatorError (G:\devconnector\node_modules\mongoose\lib\error\validator.js:29:11)
at validate (G:\devconnector\node_modules\mongoose\lib\schematype.js:1034:13)
at G:\devconnector\node_modules\mongoose\lib\schematype.js:1088:11
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (G:\devconnector\node_modules\mongoose\lib\schematype.js:1043:14)
at G:\devconnector\node_modules\mongoose\lib\document.js:2133:9
at process._tickCallback (internal/process/next_tick.js:61:11)
message: 'Path `name` is required.',
name: 'ValidatorError',
properties: [Object],
kind: 'required',
path: 'name',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true } },
_message: 'users validation failed',
name: 'ValidationError' }
答案 0 :(得分:1)
在您的代码中,我可以看到您将newUser
设置为User()模型对象,然后将其设置为普通的javascript对象。语法上也是错误的。
基本上,您需要使模型对象具有值。
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar,
password: req.body.password
});
答案 1 :(得分:0)
解决方案很简单,现在和将来避免使用额外的参数,你不需要它们
const userSchema = mongoose.Schema({ 电子邮件:字符串, 用户名:字符串, 密码:字符串, googleId:字符串, avatar_url:字符串, });