首页 > 解决方案 > 使用带有rest api的node js在另一个表中添加用户名和密码

问题描述

我有一个模型是该模型中的用户我添加了电子邮件、用户名、密码和名称,当我在 rest API 的帮助下使用节点 JS 插入此数据时,因此条件所有 4 条记录都存储在一个表中,但我想要电子邮件和姓名存储在注册表中,用户名和密码存储在登录表中,当我使用邮递员发出登录请求时,它带有用户名和密码凭据,它给出了成功的响应。

我是 Node 新手

我的控制器是

exports.user_signup = (req, res, next) => {
User.find({ username: req.body.username })
.exec()
.then(user => {
  if (user.length >= 1) {
    return res.status(409).json({
      message: "Mail exists"
    });
  } else {
    bcrypt.hash(req.body.password, 10, (err, hash) => {
      if (err) {
        return res.status(500).json({
          error: err
        });
      } else {
        const user = new User({
          _id: new mongoose.Types.ObjectId(),
          username: req.body.username,
          password: hash,
          email: req.body.email,
          contact: req.body.contact,
        });

        user
          .save()
          .then(result => {
           // console.log(result);
            res.status(201).json({
              message: "User created"
            });
          })
          .catch(err => {
            console.log(err);
            res.status(500).json({
              error: err
            });
          });
      }
    });
  }
});
};

我的 Postman post 方法是 JSON 格式

{
   "username":"tene",
   "password":"tene",
   "email":"tene@gmail.com",
   "contact":1234567890
  }

标签: node.jspostmanrest

解决方案


你可以试试这个:

import mongoose from 'mongoose'

const { Schema } = mongoose

const userSchema = new Schema(
  {
    registrationTable : { 
      email: { type: String, required: true },
      mobileNo: { type: String, required: true }
    },
    loginTable: { 
      username: { type: String, required: true },
      password: { type: String, required: true }
    }
  },
  { timestamps: true }
)
const UserModel = mongoose.model('User', userSchema)

如果您想将注册和登录表作为对象或数组,这将取决于您,但这肯定会有所帮助。

required: true将用于,您需要该值,如果您不想要某些值,请删除它。


推荐阅读