简体   繁体   English

无法使用 Nodejs 更新 mongoDB 中的文档值

[英]Can't update document value in mongoDB with Nodejs

I'm trying to get the value of a field form that I'm sending to a subroute and use it to update the database collection.我正在尝试获取要发送到子路由的字段表单的值,并使用它来更新数据库集合。 I can get the value of the form perfectly and work with it, the problem comes when I only want to update the fields that are not empty.我可以完美地获取表单的值并使用它,当我只想更新非空字段时问题就来了。

server.js服务器.js

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('/');
});

MongoDB error on syntax after only placing data in the description field: MongoDB 仅在描述字段中放置数据后出现语法错误:

{ '$set': [ { description: 'helloasd' } ] }

Solution by Palladium02: Palladium02 的解决方案:

    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;
    }
    let data = { $set: test };
    console.log(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM