在尝试使用nodejs和mongoose注册用户时,我在dot notation
上User.findOne(email: res.body.email)
上说了一个错误。我试过这个
User: User.findOne(...)
但是,它会在运行时从postman发送post请求时引发以下错误
(node:13952) UnhandledPromiseRejectionWarning: ReferenceError: body is not defined
at User.User.findOne.then.user (C:\Users\Aman\Desktop\qwerty\routes\api\users.js:14:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing ins
ide of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejectio
n id: 1)
这是我的密码
const User = require("../../Models/User");
router.post("/register", (req, res) => ({
User.findOne({ email: req.body.email }).then(user => {
if (user) {
show email registered before message
} else {
do something
});
const newUser = new User({
name: req.body.name,
email: req.body.email,
avatar: req.body.avatar,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
newUser.password = hash;
newUser
.save()
});
});
}
})
}));
发布于 2019-02-14 09:34:00
删除函数(req, res) =>
正文外的括号。它应该是这样的:
router.post("/register", (req, res) => {
User.findOne({ email: req.body.email })
// other code inside
});
() => ({})
将期望返回一个对象文字表达式,例如JSON对象。() => {}
将在函数体中执行语句。
在MDCN:functions#Syntax上阅读更多信息
发布于 2019-02-14 09:34:19
在箭头函数中,在这里使用的语法
(req, res) => ({})
返回一个对象。
const foo = () => ({foo: 'bar'});
console.log(foo());
这是一个缩写
const foo = () => {
return {
foo: 'bar'
}
};
console.log(foo());
因此,您要么需要修复代码才能真正返回有效的对象,要么在开始时删除({
,在函数的末尾删除})
。
router.post("/register", (req, res) => {
User.findOne({ email: req.body.email })
// ...
});
https://stackoverflow.com/questions/54686733
复制相似问题