我正试图在一个图集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的其他新手从我的错误中吸取教训,如果有人重复我的STUPID错误,我希望他们能找到并修复它。

最新更新