簡體   English   中英

我正在嘗試在 atlas mongoDB 上添加多個用戶

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

我創建了一個 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);

我使用此功能進行注冊:

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

我驗證:

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()
}

我使用路線:

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

問題是當我嘗試使用郵遞員創建第二個用戶時:

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

我收到錯誤:

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

請幫忙 !!!!! 這個錯誤讓我發瘋,我不知道我做錯了什么

在逐行運行我的代碼多次后,我發現代碼很好,問題出在我的 atlas mongodb 數據庫中。 所以我是 nodejs 和 mongo 的新手,我嘗試學習,當我在 atlas 中創建我的第一個 mongodb 數據庫時,我沒有注意命名我的數據庫,所以它的默認名稱為 . 我回到了 atlas mongodb 並創建了一個新數據庫(集群),將其命名為 TEST ,復制鏈接,進入我的 dotenv 文件,將鏈接粘貼到我的 MONGO_URI 重新啟動服務器,然后所有代碼運行良好,現在我可以添加盡可能多的我想要的用戶。 我希望 mongodb 和 nodejs 的其他新手從我的錯誤中吸取教訓,如果有人重復我的愚蠢錯誤,我希望他們能找到並修復它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM