Node.js中MongoDB仅更新非空字段时出现语法错误
MongoDB非空字段更新语法错误修复
问题说明
通过子路由接收表单值更新MongoDB集合时,仅更新非空字段触发语法错误。控制台输出的错误更新语句显示$set的值为数组类型,不符合MongoDB语法要求。
原代码
app.post("/updProject", function(request, response){ var project = { name : request.body.project_name }; var test = {}; if(request.body.new_project_name != ""){ test['name'] = request.body.new_project_name; } if(request.body.new_project_description != ""){ test['description'] = request.body.new_project_description; } if(request.body.new_project_site != ""){ test['view'] = request.body.new_project_site; } if(request.body.new_project_code != ""){ test['code'] = request.body.new_project_code; } var data = { $set: [test] }; console.log(data); collection.updateOne(project, data, function(error, collection){ if (error) throw error; console.log("Record edited successfully"); }); return response.redirect('/'); });
错误信息
仅填入description字段时,控制台输出:
{ '$set': [ { description: 'helloasd' } ] }
此时触发MongoDB语法错误。
错误原因
MongoDB的$set操作符要求接收纯对象作为参数,你错误地将test对象包裹在数组中,导致$set的值为数组类型,违反了语法规则。
修复方案
将var data = { $set: [test] };修改为var data = { $set: test };,直接传递test对象给$set。
修复后代码
app.post("/updProject", function(request, response){ var project = { name : request.body.project_name }; var test = {}; if(request.body.new_project_name != ""){ test['name'] = request.body.new_project_name; } if(request.body.new_project_description != ""){ test['description'] = request.body.new_project_description; } if(request.body.new_project_site != ""){ test['view'] = request.body.new_project_site; } if(request.body.new_project_code != ""){ test['code'] = request.body.new_project_code; } // 移除数组包裹,直接传入test对象 var data = { $set: test }; console.log(data); collection.updateOne(project, data, function(error, collection){ if (error) throw error; console.log("Record edited successfully"); }); return response.redirect('/'); });
优化建议
- 空值判断可以更严谨,比如用
if(request.body.new_project_name?.trim())过滤仅含空格的输入 - 推荐使用
async/await替代回调函数,优化错误处理和代码可读性:
app.post("/updProject", async function(request, response){ try { var project = { name : request.body.project_name }; var test = {}; if(request.body.new_project_name?.trim()){ test['name'] = request.body.new_project_name; } if(request.body.new_project_description?.trim()){ test['description'] = request.body.new_project_description; } if(request.body.new_project_site?.trim()){ test['view'] = request.body.new_project_site; } if(request.body.new_project_code?.trim()){ test['code'] = request.body.new_project_code; } var data = { $set: test }; await collection.updateOne(project, data); console.log("Record edited successfully"); response.redirect('/'); } catch (error) { console.error(error); // 这里可以添加错误页面跳转或提示 response.status(500).send("更新失败"); } });
内容的提问来源于stack exchange,提问作者LautaroColella
相关产品推荐
相关产品推荐

