Home > Enterprise >  Can't update document value in mongoDB with Nodejs
Can't update document value in mongoDB with Nodejs

Time:08-08

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' } ] }

CodePudding user response:

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);
  • Related