Home > Enterprise >  Concatenating string using sign throws syntax error in Nodejs using mongodb
Concatenating string using sign throws syntax error in Nodejs using mongodb

Time:07-27

I am trying to concatenate some strings in a mongodb application with nodejs like so:

    let attach_dev = await db.collection("devices").updateOne(
    {
        '_id': deviceId
    },
    {
        $set: {'attachedObjectIds.0' : objId} // Works..
        //$set: {'attachedObjectIds.'   '0' : objId} // does not work
        //$set: {'attachedObjectIds.'   iface.toString() : objId} // does not work
    }
);

nodejs returns with a SyntaxError in both two cases:

            $set: {'attachedObjectIds.'   '0' : objId}
                                        ^

SyntaxError: Unexpected token ' '
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)
    at internal/main/run_main_module.js:17:47

What am I doing wrong ?

CodePudding user response:

The problem is not related to MongoDB, it's related to Javascript syntax. attachedObjectIds.0 is a key inside the object that you define for $set, concatenation inside the key can not be done without using [], you can do it like that

let attach_dev = await db.collection("devices").updateOne(
                {
                    '_id': deviceId
                },
                {
                   $set: {['attachedObjectIds.'   '0'] : objId} 
                }
);
  • Related