javascript - 通过 POST 请求更新猫鼬模式的属性
问题描述
我想在用户进行身份验证时更新用户的位置。
city
当用户发布 API 路由 /login 时,需要更新该属性。
我似乎无法弄清楚如何更新架构,因为我已经在堆栈上尝试了多种解决方案。有人可以帮我吗
POST 请求:包含 api 路由 /login
router.post('/login',cors(), async (req, res) => {
try {
const { email, password, city } = req.body;
if (!isEmail(email)) {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Email must be a valid email address',
},
],
});
}
if (typeof password !== 'string') {
return res.status(400).json({
errors: [
{
title: 'Bad Request',
detail: 'Password must be a string',
},
],
});
}
const user = await User.findOne({ email });
if (!user) {
throw new Error();
}
const userId = user._id;
user.update({
city: req.user.city
},{
$set: {
"User.city": req.body.city
}
}, function (err, user) {
if (err) throw error
console.log(user)
console.log("update user complete")
});
const passwordValidated = await bcrypt.compare(password, user.password);
if (!passwordValidated) {
throw new Error();
}
const session = await initSession(userId);
res
.cookie('token', session.token, {
httpOnly: true,
sameSite: true,
maxAge: 1209600000,
secure: process.env.NODE_ENV === 'production',
})
.json({
title: 'Login Successful',
detail: 'Successfully validated user credentials',
csrfToken: session.csrfToken,
token: session.token,
city : user.city
});
} catch (err) {
res.status(401).json({
errors: [
{
title: 'Invalid Credentials',
detail: 'Check email and password combination',
errorMessage: err.message,
},
],
});
}
});
UserSchema:这是用户的猫鼬模式
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
minlength: 1,
trim: true,
unique: true, //each registered email must be unique
},
password: {
type: String,
required: true,
minlength: 8,
},
city:{
type: String,
},
module.exports = mongoose.model('User', UserSchema);
解决方案
你应该注意几件事。
- 你应该得到一个文件
userId
而不是city
. 获取文档city
并不能保证您更新正确的文档。因为同一个城市可能有多个文件。 - 不要与
user
和混淆User
。您有User
作为模型和user
从数据库返回的对象。 User.city
是不正确的,你应该city
只使用。
检查以下代码:
const user = await User.findOne({ email });
if (!user) {
throw new Error();
}
const userId = user._id;
User.update({ // Use `model` instead returned object.
_id: userId // Use `_id` instead of `city` to get record.
},{
$set: {
"city": req.body.city // Only `city`, you should use instead of `User.city`
}
}, function (err, user) {
if (err) throw error
console.log(user)
console.log("update user complete")
});
推荐阅读
- javascript - 使用 setInterval 无法在异步函数中达到值 - JavaScript
- python - 为什么在 Django App 中显示“django.core.management.base.SystemCheckError”& 无法运行服务器
- node.js - 反应原生无法解析模块util
- vue.js - 如何解决“通过导航守卫从'/'到'/dashboard'时重定向”错误?
- reactjs - React useEffect:如何清除Interval?
- elasticsearch - 如何在特定 ID 上设置不条件以不在 DSL 查询中搜索
- kotlin - Kotlin UInt 和 JUnit
- node.js - 如何将字符串推送到 dynamoDB 中的数组中?
- reactjs - 为反应 charjs2 设置选项/自定义标签
- javascript - 状态未使用 useState 设置方法更新