0

I need to join two strings in the name of the object in for loop in mongoose and expressjs like in example:

for(var i = 0; i < 2; i++)
{
    EnrollSessions.update({ CookieId: req.cookies.UserEnrollSession },
    {$set: {"Files.File"+i+".RealName": file.originalname},
function (err,data) {
                    console.log(data);
                });
}   

As a result i need update value of Files.File1.Realname, Files.File2.Realname.

Is it possible? Thank you for help in advance.

Wojtokuba
  • 21
  • 3

1 Answers1

0

In your example the for loop runs with i values 0 and 1 which would rename File0 and File1.

You can use "Files.File"+ (i + 1) +".RealName".

A better approach would be to create the update object in the for loop and the send it to mongo afterwards.

let obj = {

};

for(var i = 0; i < 2; i++)
{
    let name = "Files.File" + (i + 1) + ".RealName";
    obj[name] = file.originalname;
}   

    EnrollSessions.update({ CookieId: req.cookies.UserEnrollSession },
    {$set: obj},
function (err,data) {
                    console.log(data);
                });

Or, if there are only 2 files you can hard code them by hand in the same update object instead of the for loop.

v2d
  • 56
  • 1
  • 5