简体   繁体   English

我正在尝试在 atlas mongoDB 上添加多个用户

[英]i am trying to add multiple users on a atlas mongoDB

I have created a rest api and I am trying to add multiple users to atlas mongodb I use this schema我创建了一个 rest api,我正在尝试将多个用户添加到 atlas mongodb 我使用这个模式

const mongoose = require('mongoose');
const { v1: uuidv1 } = require('uuid');
const crypto = require('crypto')

const userSchema = new mongoose.Schema({
    // _id: mongoose.Types.ObjectId, 
    name: {
        type: String,
        // trim: true,
        unique: true,
        required: true,
        index: true
  
    },
    email: {
        type: String,
        // trim: true,
        required: true,
        unique: true,
    },
    hashed_password: {
        type: String,
        trim: true,
        required: true
    },
    salt: String,
    created: {
        type: Date,
        default: Date.now
    },
    updated: Date,
    
})


// VIRTUAL FIELD
userSchema.virtual('password')
    .set(function(password){
        //create temporary variable called _password
        this._password = password
        //generate a timestamp
        this.salt = uuidv1();
        //encryptPassword
        this.hashed_password = this.encryptPassword(password)
    })
    .get(function(){
        return this._password
    })

///methods 
userSchema.methods = {
    authenticate: function(plainText){
        return this.encryptPassword(plainText) === this.hashed_password
    },

    encryptPassword : function(password){
        if(!password) return "";
        try{
            return crypto.createHmac('sha256', this.salt)
            .update(password)
            .digest('hex');
        } catch(err){
            return ""
        }
    }
}

module.exports = mongoose.model('User', userSchema);

I use this function to sign up :我使用此功能进行注册:

exports.signup = async (req, res) => {
    const userExists = await User.findOne({email : req.body.email})
    if(userExists) return res.status(403).json({
        error: "EMAIL is TAKEN"
    })
    const user = await new User(req.body)
    await user.save()
        .then(result => {res.json({result: result})})
        .catch(err => res.json({err : err}))
}

I validate :我验证:

exports.userSignupValidator = (req, res, next) => {
    //name is not null and its between 4 and 10 characters
    req.check('name', 'name is required').notEmpty();
    //email is not null, valid and NORMALIZED -> we will use method chaining
    req.check('email', 'please enter valid email')
        .matches(/.+\@.+\..+/)
        .withMessage('email must contain @')
        .isLength({
            min: 4,
            max: 2000
        })

    //check for password
    req.check('password', 'Password is required').notEmpty();
    req.check('password').isLength({
        min: 6,
    }).withMessage('password must be minimum 6 char long').matches(/\d/).withMessage('must contain a number')
    //check for errors
    const error = req.validationErrors()

    ////////if error apears show the first one as they appear
    if(error){
        const firstError = error.map((error) => error.msg)[0]
        return res.status(400).json({error: firstError})
    }

    ////proceed to next middleware
    next()
}

and I use the route :我使用路线:

const express = require('express'); //bring in express 
const postController = require('../controlers/postControler')  //brings everything that is exported from the postControler FILE and becomes a OBJECT
const router = express.Router();
const validator = require('../validator');
const signup = require('../controlers/authControler');
const userById = require('../controlers/userControler');

router.get('/',  postController.getPosts)
router.post('/post', signup.requireSignIn, validator.createPostValidator, postController.createPost)
router.get('/test' , postController.test)
router.post('/signup', validator.userSignupValidator, signup.signup)
router.post('/signin', signup.signin)
router.get('/signout', signup.signout)
router.get('/lahoha', userById.getUsers)
////find the user by id with params 
////any routes containing :userId our app will first execute userById()
router.param('userId', userById.userById);
///////////////////////////////////////////////
module.exports = router

the problem is when I try to create a second user with postman with :问题是当我尝试使用邮递员创建第二个用户时:

{
    "name": "petru",
    "email": "petru@gmail.com",
    "password": "notazece10"
}

I get the error :我收到错误:

{
    "err": {
        "driver": true,
        "name": "MongoError",
        "index": 0,
        "code": 11000,
        "keyPattern": {
            "username": 1
        },
        "keyValue": {
            "username": null
        }
    }
}

Please help !!!!!请帮忙 !!!!! this error is driving me crazy, I don't know what I'm doing wrong这个错误让我发疯,我不知道我做错了什么

after running thru my code multiple times line by line i found out the code is fine , the problem was in my atlas mongodb database.在逐行运行我的代码多次后,我发现代码很好,问题出在我的 atlas mongodb 数据库中。 So i am new to nodejs and mongo , and i try to learn , when i created my first mongodb database in atlas i did not pay attention to naming my database so it had the default name of .所以我是 nodejs 和 mongo 的新手,我尝试学习,当我在 atlas 中创建我的第一个 mongodb 数据库时,我没有注意命名我的数据库,所以它的默认名称为 . I went back to atlas mongodb and i made a new database ( cluster) , named it TEST , copied the link, went into my dotenv file paste the link to my MONGO_URI restarted the server and then all code worked fine now i can add as many users as i want.我回到了 atlas mongodb 并创建了一个新数据库(集群),将其命名为 TEST ,复制链接,进入我的 dotenv 文件,将链接粘贴到我的 MONGO_URI 重新启动服务器,然后所有代码运行良好,现在我可以添加尽可能多的我想要的用户。 I hope other newcomers to mongodb and nodejs learn from my mistake and if someone ever repeats my STUPID mistake i hope they find this and fix it.我希望 mongodb 和 nodejs 的其他新手从我的错误中吸取教训,如果有人重复我的愚蠢错误,我希望他们能找到并修复它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试将节点 js 与 mongoDB Atlas cloud 连接时出现 UnhandledPromiseRejectionWarning 错误 - I am getting UnhandledPromiseRejectionWarning error when trying to connect node js with mongoDB Atlas cloud 我无法将数据保存到我的 mongodb Atlas 数据库 - I am unable to save data to my mongodb Atlas database 我无法连接到 mongodb atlas 集群。 我得到了如下所示的 MongooseError - I am unable to making connection to mongodb atlas cluster . i got the MongooseError which as following 尝试使用 nodeJs 连接到 mongodb Atlas - trying to connect to mongodb Atlas using nodeJs 我正在尝试将 Angular 连接到 MongoDB - I am trying to connect Angular to MongoDB 我正在尝试将 mongodb 服务器与节点连接 - I am trying to connect mongodb server with node 我无法从 a2hosting 共享 NodeJS 主机连接 Atlas MongoDB Cloud - I am not able to connect Atlas MongoDB Cloud from a2hosting shared NodeJS hosting 我正在尝试在 nodejs 中的 mongodb (mongoose) 中的键值对中添加新值 - I am trying to add new values to key value pair in mongodb (mongoose) in nodejs 你好,我想在 2 分钟内从 mongoDB atlas 中删除新用户,如果他们不验证他们的电话号码,我认为 TTL 是方式 - Hello , I want to remove new users from mongoDB atlas within 2 minutes if they do not verify their phone number , I think TTL is the way 我正在使用 mongoDB 图集,但出现了 MongoServerError。 当我在没有 .env 文件的情况下使用时,一切都很好,但是使用 env 会抛出错误 - I am using mongoDB atlas and I am getting MongoServerError. When I am using without .env file every thing is fine but with env it is throwing error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM