简体   繁体   中英

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

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:

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

Solution by 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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