Search code examples
node.jsmongodbnedb

Can't update elements which are inside the array


Let's say I have this

userinfo={
    userDetails:
    {
        username:"",
        password:"",
        cookie:"",
        firstname:"",
        lastname:"",
        phonenumber:"",
        postalcode:"",
        country:""
    },
    applicationsInfo:[
        {
            application:"",
            consumerKey:"",
            accessToken:""
        }
    ]
}

First I created user and latter I am to update applicationsInfo section when user creates an application. First I tried this way and It works

var consumerKey="asdyfsatfdtyafydsahyadsy";
var findCon={"userDetails.username":"someName"};
db.find(findCon,function(err,docs){
    if(err){
        console.log(err);
    }else{
        var updateCon={$set:{"applicationsInfo.0.consumerKey":consumerKey}};
        db.update(findCon,updateCon,{},function(err,docs){
            console.log(docs);
        });
    }
});

But actually what I want is update some selected one I tried that in this way.

........
var appNum=0;
var updateCon={$set:{"applicationsInfo."+appNum+".consumerKey":consumerKey}};

then I start my node server then I got error like this.

/home/jobs/nodeserver/routes/initusers.js:180
             "applicationsInfo."+appNum+
                                ^
             SyntaxError: Unexpected token +
                   at Module._compile (module.js:439:25)
                   at Object.Module._extensions..js (module.js:474:10)
                   at Module.load (module.js:356:32)
                   at Function.Module._load (module.js:312:12)
                   at Module.require (module.js:364:17)
                   at require (module.js:380:17)

Solution

  • You need to set it the below way:

    var appNum = 0;
    var updateCon = {$set:{}};
    updateCon.$set["applicationsInfo."+appNum+".consumerKey"] = 1;
    

    Setting an expression ("applicationsInfo."+appNum+".consumerKey") as key of an object during initialization is not allowed in java script.