通过POST请求更新猫鼬模式的属性

时间:2018-11-26 18:23:02

标签: javascript mongodb mongoose mean-stack

我想在用户进行身份验证时更新用户的位置。

用户POST API路由/ login时,属性city需要更新。

当我已经在堆栈上尝试了多个解决方案时,我似乎无法弄清楚如何更新架构。有人可以帮我吗

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);

1 个答案:

答案 0 :(得分:1)

您应该注意的事情。

  1. 您应该使用userId而不是city来获取文档。通过city获取文档并不能保证您更新正确的文档。因为可能有多个文件位于同一个城市。
  2. 不要与userUser混淆。您将User作为模型,将user作为数据库的返回对象。
  3. 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")
});
相关问题