你好。
在充满回调的 MongoDB Driver 上有一个简单的注册,我决定使用 asyc / await 重写。但是有一个错误。它与什么有关,我不明白。有人可以解释吗?谢谢)
蒙戈错误:
index: name_1 dup key: { : null }E11000 重复键错误集合:FirstApp.users
编码:
const config = require ('../config');
const mongodb = require ('mongodb');
const ObjectId = require('objectid');
const express = require ('express');
const router = express.Router();
const MongoClient = mongodb.MongoClient;
const DBurl = config.DBurl;
const SaveUser = async function (UserEmail, UserPassword, sessionID) {
const User = {
//_id: new ObjectId(),
"UserEmail": UserEmail,
"UserPassword": UserPassword,
"SessionID": sessionID,
};
console.log(User);
try {
const db = await MongoClient.connect(DBurl);
const collection = db.collection('users');
//collection.createIndex({"name" : 1}, {"unique" : true});
const result = await collection.insertOne(User);
if (result.acknowledged)
return {save: true};
else
return {save: false};
} catch (e) {
return e;
}
};
const Register = router.post("/", async (req, res) => {
const UserEmail = req.body.UserEmail;
const UserPassword = req.body.RegisterPassword;
const UserConfirmPassword = req.body.confirmPassword;
const sessionID = req.sessionID;
if (UserPassword === UserConfirmPassword) {
const result = await SaveUser(UserEmail, UserPassword, sessionID);
result.save ?
res.status(200)
.json({isBusy: false}) :
res.status(500)
.json({error: result, isBusy: true});
}
else if(UserEmail || UserPassword || UserConfirmPassword === undefined)
res.status(400)
.send('Bad request');
else if (UserConfirmPassword !== UserPassword)
res.status(400)
.send('Wrong confirm password');
});
module.exports = Register;
我真笨)
我在数据库中没有字段
name
:) 但是数据库中塞满了左索引。像这样解决它:
清除数据库中的所有索引
我一定要拥有独一无二的
UserEmail
其实,仅此而已。)