使用Axios POST写入MongoDB时遇500错误及写入关注模式问题
问题:MongoDB写入成功却触发500错误,提示「No write concern mode named majority found in replica set configuration」
通过Axios POST请求向MongoDB插入用户对象,数据已成功写入集合,但本该跳转首页时触发了Axios 500状态码错误,响应提示「No write concern mode named majority found in replica set configuration」。
相关代码
UserSignUp.jsx
export default function SignUpScreen() { const navigate = useNavigate(); const { search } = useLocation(); const redirectInUrl = new URLSearchParams(search).get('redirect'); const redirect = redirectInUrl ? redirectInUrl : '/'; const [name,setName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState('') const { state, dispatch: ctxDispatch } = useContext(Store); const { userInfo } = state; const submitHandler = async e => { e.preventDefault(); if(password !== confirmPassword) { toast.error('Passwords do not match'); return; } try { const { data } = await axios.post('/api/users/signup', { name, email, password, }); ctxDispatch({ type: 'User_SignIn', payload: data }); localStorage.setItem('userInfo', JSON.stringify(data)); navigate(redirect || '/'); } catch (err) { toast.error(getError(err)); console.log(err); } }; useEffect(() => { if (userInfo) { navigate(redirect); } }, [navigate, userInfo, redirect]); return ( <Container className='small-container'> <Helmet> <title>Sign Up</title> </Helmet> <h1 className='my-3'>Sign Up</h1> <Form onSubmit={submitHandler}> <Form.Group className='mb-3' controlId='name'> <Form.Label>Name</Form.Label> <Form.Control required onChange={e => setName(e.target.value)} /> </Form.Group> <Form.Group className='mb-3' controlId='email'> <Form.Label>Email</Form.Label> <Form.Control type='email' required onChange={e => setEmail(e.target.value)} /> </Form.Group> <Form.Group className='mb-3' controlId='password'> <Form.Label>Password</Form.Label> <Form.Control type='password' required onChange={e => setPassword(e.target.value)} /> </Form.Group> <Form.Group className='mb-3' controlId='confirmPassword'> <Form.Label>Confirm Password</Form.Label> <Form.Control type='password' required onChange={e => setConfirmPassword(e.target.value)} /> </Form.Group> <div className='mb-3'> <Button type='submit'>Sign Up</Button> </div> <div className='mb-3'> Already have an account?{' '} <Link to={`/signin?redirect=${redirect}`}>Sign-In</Link> </div> </Form> </Container> ); }
userRouter.js
userRouter.post( '/signup', expressAsyncHandler(async (req, res) => { const newUser = new User({ name: req.body.name, email: req.body.email, password: bcrypt.hashSync(req.body.password), }); try { const user = await newUser.save(); res.send({ _id: user._id, name: user.name, email: user.email, isAdmin: user.isAdmin, token: genarateToken(user), }); } catch (err) { res.status(500).send(err) } }) ); export default userRouter;
UserModel.js
const userSchema = new mongoose.Schema( { name: {type:String, required: true}, email: {type:String, required: true, unique:true}, password: {type:String, required: true}, isAdmin: {type: Boolean, default: false,required: true}, }, { timestamps: true } ) const User = mongoose.model("User", userSchema); export default User;
App.js路由
<Routes> <Route path='/product/:slug' element={<ProductScreen />} /> <Route path='/cart' element={<CartScreen />} /> <Route path='/signin' element={<SignInScreen />} /> <Route path='/signup' element={<SignUpScreen />} /> <Route path='/shipping' element={<ShippingAddressScreen />} /> <Route path='/' element={<HomeScreen />} /> </Routes>
.env中的MongoURI
MongoURI = mongodb+srv://Ecom:password@cluster0.c0ita7f.mongodb.net/EcomDB?retryWrites=true&w=majority
错误信息
控制台错误
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} code: "ERR_BAD_RESPONSE" config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} message: "Request failed with status code 500" name: "AxiosError" request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response: {data: {…}, status: 500, statusText: 'Internal Server Error', headers: {…}, config: {…}, …} [[Prototype]]: Error
Postman错误
{ "code": 79, "codeName": "UnknownReplWriteConcern", "errInfo": { "writeConcern": { "w": "majority,", "wtimeout": 0, "provenance": "clientSupplied" } }, "result": { "n": 1, "electionId": "7fffffff0000000000000067", "opTime": { "ts": { "$timestamp": "7136856325794824195" }, "t": 103 }, "writeConcernError": { "code": 79, "codeName": "UnknownReplWriteConcern", "errmsg": "No write concern mode named 'majority,' found in replica set configuration", "errInfo": { "writeConcern": { "w": "majority,", "wtimeout": 0, "provenance": "clientSupplied" } } }, "ok": 1, "$clusterTime": { "clusterTime": { "$timestamp": "7136856325794824195" }, "signature": { "hash": "OlulLu5s5TwSvEO60v4+6td/yt8=", "keyId": { "low": 7, "high": 1648401224, "unsigned": false } } }, "operationTime": { "$timestamp": "7136856325794824195" } } }
解决方案
从Postman错误响应能直接看到问题根源:writeConcern的w参数值是"majority,"(多了个逗号)。MongoDB无法识别这个带逗号的写关注模式,所以触发了500错误,尽管数据实际已经写入成功。
修复方法任选其一:
- 显式设置mongoose连接的写关注:
在数据库连接代码中添加writeConcern配置,覆盖默认的错误参数:
mongoose.connect(process.env.MongoURI, { writeConcern: { w: 'majority' } });
- 在保存文档时指定写关注:
修改userRouter.js里的save方法,添加正确的写关注选项:
const user = await newUser.save({ writeConcern: { w: 'majority' } });
- 检查环境变量读取问题:
确认.env文件中的MongoURI没有被错误解析,比如是否有多余的空格或符号。你的URI看起来格式正确,但某些情况下环境变量读取可能会引入额外字符,可直接在代码中打印process.env.MongoURI验证。
内容的提问来源于stack exchange,提问作者Krishnadev. V
相关产品推荐
相关产品推荐

